euther
euther

Reputation: 2676

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.

Upvotes: 5

Views: 617

Answers (5)

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

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);

Upvotes: 3

Austin Salonen
Austin Salonen

Reputation: 50215

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.

Upvotes: 0

Rob
Rob

Reputation: 45761

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,

Upvotes: 0

David Morton
David Morton

Reputation: 16505

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

Upvotes: 0

João Angelo
João Angelo

Reputation: 57658

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);

Upvotes: 7

Related Questions