2012-02-04 114 views
4

我可以用下面的LINQ表達式來計算一個單詞出現的次數如下:使用LINQ來計數字符串中的子字符串?

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

但是,如果我在尋找什麼「和和」,有沒有使用LINQ來算話的方式不使用拆分。這些方法中的任何一種都需要更長的O(n)?

+2

您發佈不編譯代碼...你的意思是'INT J = test.Split(」「).Count之間(X => X == 「而」);'? – 2012-02-04 20:18:38

+0

代碼中的linq表達式在哪裏? – 2012-02-04 20:23:00

+0

@Peri Count擴展方法是給定表達式的linq部分。 – phoog 2012-02-04 23:16:53

回答

5

您可以使用正則表達式:

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

BTW,你要允許重複出現?即如果你正在尋找「And And」,你認爲test包含1或2次出現?

+1

什麼是演員要求? – 2012-02-04 20:21:54

+4

@Peri,這是因爲'MatchCollection'實現了非泛型的'IEnumerable',但不是'IEnumerable ','Count'只能用於通用版本。 – 2012-02-04 20:28:58

+1

如果您正在查找的字符串可能包含它們,請不要忘記轉義特殊的正則表達式字符。 – svick 2012-02-04 22:21:57

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; 
    }