使用LINQ计数字符串中的子? [英] Using linq to count substrings in a string?

查看:106
本文介绍了使用LINQ计数字符串中的子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I could use the following linq expression to count the number of occurrences of a word as follows:

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

但是如果我正在搜索And And,有没有办法使用linq字不使用拆分。

However what if I was searching for "And And", Is there a way to use linq to count words without using split. Do any of these methods take longer the O(n)?

推荐答案

您可以使用正则表达式:

You can use a regular expression:

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

BTW,您要允许重叠发生吗?如果你在寻找And And,你认为 test 包含1次或2次吗?

BTW, do you want to allow overlapping occurrences? i.e. if you're looking for "And And", do you consider that test contains 1 or 2 occurrences of it?

这篇关于使用LINQ计数字符串中的子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆