2010-02-24 36 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; 

您可以轻松地调整此如有必要使用几个不同的字符串。

相关问题