Counting substrings in string []

For a String array such as:

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

I need to calculate how often the bmw substring occurs in this array. In this example, this happens 2 times.

How to write this in C #?

I also want to ignore the symbol of capital,

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

then the result of the count is 3.

what should I do?

#

Thanks for the reply to everyone.

+4
source share
6 answers

Try:

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

The following code will return a counter of case-insensitive entries (as indicated by the author in the comments):

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

More on string comparisons can be found here .

+15
source

Without LINQ

 int counter = 0; foreach(string item in string_array) { if(item.IndexOf("bmw") > -1){ counter++; } } 
+5
source

You can use Linq for this, for example:

 var s = new string[] {"bmw", "1bmw"}; var result = s.Where(o=>o.Contains("bmw")).Count(); 
+3
source

If you are using C # 3, you can use LINQ:

 var strings = {"bmw"," ","1bmw"," "}; var count = string.Where( s => s.IndexOf( "bmw" ) > -1 ).Count(); 

Otherwise, the loop will also work:

 string[] strings = {"bmw"," ","1bmw"," "}; int count = 0; foreach( string s in strings ) { if( s.IndexOf( "bmw" > -1 ) ) { count++; } } 
+1
source

One method using LINQ

 static int CountOfString(IEnumerable<string> items, string substring, bool isCaseSensitive) { StringComparison comparison = StringComparison.InvariantCulture; if (!isCaseSensitive) comparison = StringComparison.InvariantCultureIgnoreCase; return items.Count(item => item.IndexOf(substring, comparison) > -1); } 

Using

 string[] items = { "bmw", " ", "1bmw", " " }; int count = CountOfString(items, "bmw", false); 
+1
source

Case insensitive makes it somewhat more verbose, but still quite compact, using the following:

 var str = new sting[]={"bmw", "", "BMw","1bmw"}; var count = str.Count(s => s.IndexOf("bmw", StringComparison.InvariantCultureIgnoreCase) > -1); 
+1
source

Source: https://habr.com/ru/post/1307543/


All Articles