使用linq计算字符串中的子字符串?

我可以使用以下linq表达式来计算单词出现的次数,如下所示:

string test = "And And And"; int j = test.Split(' ').Count(x => x.Contains("And")); 

然而,如果我正在搜索“And And”,有没有办法使用linq来计算单词而不使用split。 这些方法中的任何一种都需要更长的O(n)吗?

您可以使用正则表达式:

 string test = "And And And"; int j = Regex.Matches(test, "And").Cast().Count(); 

顺便说一句,你想允许重叠发生吗? 即如果您正在寻找“And And”,您认为该test包含1或2次出现吗?

您可以使用IndexOf :

 string what = "And"; int count = 0; int pos = -what.Length; for (;;) { pos = input.IndexOf(what, pos + what.Length); if (pos == -1) break; count++; } 

这不是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; }