使用LINQ来计数字符串中的子字符串?
我可以用下面的LINQ表达式来计算一个单词出现的次数如下:使用LINQ来计数字符串中的子字符串?
string test = "And And And";
int j = test.Split(' ').Count(x => x.Contains("And"));
但是,如果我在寻找什么“和和”,有没有使用LINQ来算话的方式不使用拆分。这些方法中的任何一种都需要更长的O(n)?
您可以使用正则表达式:
string test = "And And And";
int j = Regex.Matches(test, "And").Cast<Match>().Count();
BTW,你要允许重复出现?即如果你正在寻找“And And”,你认为test
包含1或2次出现?
什么是演员要求? – 2012-02-04 20:21:54
@Peri,这是因为'MatchCollection'实现了非泛型的'IEnumerable',但不是'IEnumerable
如果您正在查找的字符串可能包含它们,请不要忘记转义特殊的正则表达式字符。 – svick 2012-02-04 22:21:57
这还不是很LINQ的,但你也可以做一个扩展方法如下图所示。这可能是比任何LINQ的解决方案更高效:
public static int CountSubStrings(this string input, string delimiter, bool ignoreCase = false)
{
int instancesNo = 0;
int pos = 0;
while((pos = input.IndexOf(delimiter, pos, ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture)) != -1)
{
pos += delimiter.Length;
instancesNo++;
}
return instancesNo;
}
您发布不编译代码...你的意思是'INT J = test.Split(”“).Count之间(X => X == “而”);'? – 2012-02-04 20:18:38
代码中的linq表达式在哪里? – 2012-02-04 20:23:00
@Peri Count扩展方法是给定表达式的linq部分。 – phoog 2012-02-04 23:16:53