首页 / .NET / 正文

.NET[C#]C#中如何计算一个字符串中单词的个数?

5132 发布于: 2018-01-17 读完约需5分钟

.NET[C#]C#中如何计算一个字符串中单词的个数?

问题摘要

比如有以下字符串,现需以斜线为分隔符,使用C#计算这个字符串的单词数共有多少:

string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;

方案一

.NET 3.5 及以上版本:

int count = source.Count(f => f == '/');

或者

int count = source.Split('/').Length - 1;

方案二

string source = "/once/upon/a/time/";
int count = 0;
foreach (char c in source) 
  if (c == '/') count++;

方案三

int count = new Regex(Regex.Escape(needle)).Matches(haystack).Count;

方案四

src.Select((c, i) => src.Substring(i)).Count(sub => sub.StartsWith(target))

方案五

string source = "/once/upon/a/time/";
int count = 0;
int n = 0;

while ((n = source.IndexOf('/', n)) != -1)
{
   n++;
   count++;
}

方案六

public static class StringExtension
{    
    /// <summary> Returns the number of occurences of a string within a string, optional comparison allows case and culture control. </summary>
    public static int Occurrences(this System.String input, string value, StringComparison stringComparisonType = StringComparison.Ordinal)
    {
        if (String.IsNullOrEmpty(value)) return 0;

        int count    = 0;
        int position = 0;

        while ((position = input.IndexOf(value, position, stringComparisonType)) != -1)
        {
            position += value.Length;
            count    += 1;
        }

        return count;
    }

    /// <summary> Returns the number of occurences of a single character within a string. </summary>
    public static int Occurrences(this System.String input, char value)
    {
        int count = 0;
        foreach (char c in input) if (c == value) count += 1;
        return count;
    }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [MySQL]MySQL数据库中从百万条数据表中随机10条数据的查询方式有哪些?

下一篇: .NET[C#]LINQ查询List集合中所有重复的元素如何实现?

本文永久链接码友网 » .NET[C#]C#中如何计算一个字符串中单词的个数?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册