Quantity of specific strings inside a string
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.
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);
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);
Regex.Matches(text, "FFF").Count;
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,
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.
精彩评论