Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many specified chars are in a string?

taken a string example as 550e8400-e29b-41d4-a716-446655440000 how can one count how many - chars are in such string?

I'm currently using:

int total = "550e8400-e29b-41d4-a716-446655440000".Split('-').Length + 1;

Is there any method that we don't need to add 1... like using the Count maybe?

All other methods such as

Contains IndexOf etc only return the first position and a boolean value, nothing returns how many were found.

what am I missing?

like image 798
balexandre Avatar asked Nov 27 '22 01:11

balexandre


1 Answers

You can use the LINQ method Enumerable.Count for this purpose (note that a string is an IEnumerable<char>):

int numberOfHyphens = text.Count(c => c == '-');

The argument is a Func<char, bool>, a predicate that specifies when an item is deemed to have 'passed' the filter.

This is (loosely speaking) equivalent to:

int numberOfHyphens = 0;

foreach (char c in text)
{
    if (c == '-') numberOfHyphens++;
}
like image 188
Ani Avatar answered Dec 17 '22 14:12

Ani