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

时间:2012-02-04 20:15:53

标签: c# linq

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

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

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

4 个答案:

答案 0 :(得分:6)

您可以使用正则表达式:

string test = "And And And";
int j = Regex.Matches(test, "And").Cast<Match>().Count();
顺便说一下,你想允许重叠发生吗?即如果你正在寻找“And And”,你认为test包含1或2次吗?

答案 1 :(得分:1)

我找到了一个聪明的解决方案,可以使用大多数 LINQ to ORM 解决服务器端问题:

string search = "foo";
int searchLength = search.Length;

var result = qry.Select(i => new { Object = i, Occurrences = (i.SomeProperty.Length - i.SomeProperty.Replace(search, "").Length) / searchLength });

想法是用空字符串替换子字符串,然后将字符串长度的差异除以搜索词的长度。

答案 2 :(得分:0)

您可以使用IndexOf

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

答案 3 :(得分:0)

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