Hi, I'm working in .net c# and I have a string text = "Whatever text FFF you can FFF imagine"; What i need is to get the quantity of times the "FFF" appears in the string text. How can i acomplished that? Thank you.
+6
A:
You can use regular expressions for this and right about anything you want:
string s = "Whatever text FFF you can FFF imagine";
Console.WriteLine(Regex.Matches(s, Regex.Escape("FFF")).Count);
João Angelo
2010-02-24 16:35:05
thank you so mucho works perfectly
rolando
2010-02-24 16:45:19
A:
Use the System.Text.RegularExpressions.Regex for this:
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,
Rob
2010-02-24 16:36:57
+2
A:
Here are 2 approaches. Note that the regex should use the word boundary \b
metacharacter to avoid incorrectly matching occurrences within other words. The solutions posted so far do not do this, which would incorrectly count "FFF" in "fooFFFbar" as a match.
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);
Ahmad Mageed
2010-02-24 16:42:34
+1 for the useful information. However the OP never specifies that he's counting words so it's a matter of interpretation.
João Angelo
2010-02-24 16:51:05
@João thanks, I +1'd you earlier before deciding to post with these additional approaches.
Ahmad Mageed
2010-02-24 16:58:11
A:
Here's an alternative to the regular expressions:
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;
You could easily tweak this to use several different strings if necessary.
Austin Salonen
2010-02-24 16:44:25