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

Sam*_*r83 5 c# linq

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

string test = "And And And";
int j = test.Split(' ').Count(x => x.Contains("And"));
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*que 6

您可以使用正则表达式:

string test = "And And And";
int j = Regex.Matches(test, "And").Cast<Match>().Count();
Run Code Online (Sandbox Code Playgroud)

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

  • @Peri,这是因为`MatchCollection`实现了非通用的`IEnumerable`,而不是`IEnumerable <Match>`,而`Count`只适用于泛型版本. (4认同)