Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting substring occurrences in string[]

Tags:

c#

Given a String array such as this:

string[]={"bmw"," ","1bmw"," "};

I need to count how often the substring bmw occurs in that array. In this example it occurs 2 times.

How do I write that in C#?

also i want to ignore the capital character,

sting[]={"bmw", "", "BMw","1bmw"}

then the count result is 3.

what should i do?

#

Thanks for everyone's answer.

like image 497
user321952 Avatar asked Nov 28 '22 23:11

user321952


1 Answers

Try:

var str = new string[] { "bmw", " ", "1bmw", " " };
var count = str.Count(s => s.Contains("bmw"));

the next code will return the count of case insensitive occurrences (as author mentioned in comments):

var count = str.Count(s =>
    s.IndexOf("bmw", StringComparison.OrdinalIgnoreCase) > -1
);

More about string comparisons could be found here.

like image 200
Oleks Avatar answered Dec 08 '22 18:12

Oleks