2010-02-24 61 views
5

我在.net c#中工作,並且我有一個字符串text =「無論您可以FFF想象什麼文本FFF」; 我需要的是獲得「FFF」出現在字符串文本中的次數。 我該如何達到這個目標? 謝謝。字符串中特定字符串的數量

+0

我相信「頻率」比「數量」更好。 – polygenelubricants 2010-02-24 16:47:22

+0

「X FFFF Y」是否計爲零,一或兩個匹配? – 2010-02-24 18:06:46

+2

@ polygenelubricants:不,「數量」在這裏比「頻率」要好。 (雖然「數字」比「數量」更習慣用法。)*數量*僅僅意味着數量。 A *頻率*意味着一個計數*,考慮到樣本的大小,它發生的頻率。例如,給定句子中「FFF」的*數量*爲2。 「FFF」的*頻率*是「每三個字」。 – 2010-02-24 18:10:13

回答

7

您可以使用正則表達式,這和右任何你想要的:

string s = "Whatever text FFF you can FFF imagine"; 

Console.WriteLine(Regex.Matches(s, Regex.Escape("FFF")).Count); 
+0

非常感謝你非常完美的作品 – euther 2010-02-24 16:45:19

0
Regex.Matches(text, "FFF").Count; 
+0

非常感謝。 – euther 2010-02-24 16:46:46

0

使用System.Text.RegularExpressions.Regex此:

string p = "Whatever text FFF you can FFF imagine"; 
var regex = new System.Text.RegularExpressions.Regex("FFF"); 
var instances = r.Matches(p).Count; 
// instances will now equal 2, 
3

這裏有2方法。請注意,正則表達式應該使用字邊界\b元字符以避免在其他字詞中錯誤地匹配事件。到目前爲止發佈的解決方案不會這樣做,這會錯誤地將「fooFFFbar」中的「FFF」計數爲匹配。

string text = "Whatever text FFF you can FFF imagine fooFFFbar"; 

// use word boundary to avoid counting occurrences in the middle of a word 
string wordToMatch = "FFF"; 
string pattern = @"\b" + Regex.Escape(wordToMatch) + @"\b"; 
int regexCount = Regex.Matches(text, pattern).Count; 
Console.WriteLine(regexCount); 

// split approach 
int count = text.Split(' ').Count(word => word == "FFF"); 
Console.WriteLine(count); 
+1

+1有用的信息。然而,OP從未指定他在計算單詞,因此這是一個解釋問題。 – 2010-02-24 16:51:05

+0

@João謝謝你,我以前曾經爲你決定使用這些附加方法發佈信息。 – 2010-02-24 16:58:11

0

下面是正則表達式的替代:

string s = "Whatever text FFF you can FFF imagine FFF"; 
//Split be the number of non-FFF entries so we need to subtract one 
int count = s.Split(new string[] { "FFF" }, StringSplitOptions.None).Count() - 1; 

您可以輕鬆地調整此如有必要使用幾個不同的字符串。

相關問題