Counting how many times a certain char appears in a string before any other char appears
I have many strings. Each string is prepended with at least 1 $
. What is the best way to loop through the chars of each string to count how many $
's there are per string.
eg:
"$hello" - 1
"$$hello" - 2
"$$h$ello" - 2
Solution 1:
You could use the Count method
var count = mystring.Count(x => x == '$')
Solution 2:
int count = myString.TakeWhile(c => c == '$').Count();
And without LINQ
int count = 0;
while(count < myString.Length && myString[count] == '$') count++;