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.
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 .
Without LINQ
int counter = 0;
foreach(string item in string_array)
{
if(item.IndexOf("bmw") > -1){
counter++;
}
}
You can use Linq for this like so:
var s = new string[] {"bmw", "1bmw"};
var result = s.Where(o=>o.Contains("bmw")).Count();
If you're using C# 3, you can use LINQ:
var strings = {"bmw"," ","1bmw"," "};
var count = string.Where( s => s.IndexOf( "bmw" ) > -1 ).Count();
Otherwise a loop will work too:
string[] strings = {"bmw"," ","1bmw"," "};
int count = 0;
foreach( string s in strings ) {
if( s.IndexOf( "bmw" > -1 ) ) {
count++;
}
}
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 it
string[] items = { "bmw", " ", "1bmw", " " };
int count = CountOfString(items, "bmw", false);
Case-insensitiveness makes it a little more verbose but still it's quite compact using following:
var str = new sting[]={"bmw", "", "BMw","1bmw"};
var count = str.Count(s => s.IndexOf("bmw", StringComparison.InvariantCultureIgnoreCase) > -1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.