繁体   English   中英

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

[英]How many specified chars are in a string?

取一个字符串例如,作为550e8400-e29b-41d4-a716-446655440000一个怎么能算多少 -字符是在这样的字符串?

我目前正在使用:

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

是否有任何我们不需要加1的方法……例如使用Count

所有其他方法,例如

Contains IndexOf等只返回第一位置和boolean值,没有什么回报有多少被发现。

我想念什么?

为此,可以使用LINQ方法Enumerable.Count (请注意, stringIEnumerable<char> ):

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

参数是Func<char, bool> ,这是一个谓词,用于指定何时将某个项目视为已“通过”过滤器。

这(宽松地说)等效于:

int numberOfHyphens = 0;

foreach (char c in text)
{
    if (c == '-') numberOfHyphens++;
}
using System.Linq;

..

int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-');
int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-');

最直接的方法是简单地遍历字符,因为这是任何一种算法都必须采取的某种方法:

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;
int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-')

要查找字符串中的“-”号,您将需要遍历字符串并检查每个字符,因此最简单的方法是编写一个执行该操作的函数。 使用Split实际上会花费更多时间,因为它无缘无故地创建了数组。

另外,它使您想做的事情变得混乱,甚至看起来您弄错了(您需要减去1)。

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM