The number of specific rows within a row

I work in .net C # and I have a line text = "Whatever FFF text you could represent FFF"; I need to get the number of times when "FFF" appears in the text text. How can i do this? Thanks.

+5
source share
5 answers

You can use regular expressions for this and the rights of everything you want:

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

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

. , \b metacharacter, . , , , "FFF" "fooFFFbar" .

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);
+3
Regex.Matches(text, "FFF").Count;
0
source

Use 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,
0
source

Here's an alternative to 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 can easily configure it to use several different strings if necessary.

0
source

All Articles