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

.NET 作者: Rector 186阅读 0评论 0收藏 收藏本文

郑重申明:本文未经许可,禁止任何形式转载

.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;
    }
}

阅读了该文章的人还浏览了...

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

发布于: 2018-01-17 09:23:00
分享扩散:

文章评论

获取验证码