代码之家  ›  专栏  ›  技术社区  ›  balexandre

一个字符串中有多少个指定字符?

  •  3
  • balexandre  · 技术社区  · 15 年前

    以字符串为例 550e8400-e29b-41d4-a716-446655440000 数数有多少 - 字符是这样的串吗?

    我正在使用:

    int total = "550e8400-e29b-41d4-a716-446655440000".Split('-').Length + 1;
    

    有没有什么方法我们不需要加1。。。就像使用 Count 也许 吧?

    所有其他方法,如

    Contains IndexOf etc只返回第一个位置 boolean 值,不返回任何内容 有多少 找到了。

    我错过了什么?

    7 回复  |  直到 15 年前
        1
  •  17
  •   Ani    15 年前

    你可以使用LINQ方法 Enumerable.Count 为此目的(注意 string 是一个 IEnumerable<char> ):

    int numberOfHyphens = text.Count(c => c == '-');
    

    争论是 Func<char, bool>

    这(粗略地说)相当于:

    int numberOfHyphens = 0;
    
    foreach (char c in text)
    {
        if (c == '-') numberOfHyphens++;
    }
    
        2
  •  5
  •   codymanix    15 年前
    using System.Linq;
    
    ..
    
    int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-');
    
        3
  •  4
  •   LukeH    15 年前
    int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-');
    
        4
  •  4
  •   Guffa    15 年前

    最直接的方法是简单地循环遍历字符,因为任何算法都必须以某种方式或另一种方式:

    int total = 0;
    foreach (char c in theString) {
      if (c == '-') total++;
    }
    

    int total = theString.Count(c => c == '-');
    

    或:

    int total = theString.Aggregate(0, (t,c) => c == '-' ? t + 1 : t)
    

    然后还有一些不确定(但效率较低)的技巧,比如删除字符并比较长度:

    int total = theString.Length - theString.Replace("-", String.Empty).Length;
    

    或者使用正则表达式查找字符的所有出现:

    int total = Regex.Matches(theString, "-").Count;
    
        5
  •  2
  •   Lee    15 年前
    int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-')
    
        6
  •  2
  •   Lou Franco    15 年前

    而且,这会让你很困惑,甚至看起来你做错了(你需要减去1)。

        7
  •  1
  •   Øyvind Bråthen    15 年前

    试试这个:

    string s = "550e8400-e29b-41d4-a716-446655440000";
    int result = s.ToCharArray().Count( c => c == '-');