Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting how many times a certain char appears in a string before any other char appears

Tags:

c#

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 
like image 651
mubar Avatar asked Mar 17 '11 14:03

mubar


People also ask

How do you count the number of occurrences of a substring in a string?

count() Return Value count() method returns the number of occurrences of the substring in the given string.

How do you count specific occurrence of character in a string?

Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string.

How do you find the number of occurrences in a string?

One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.


2 Answers

You could use the Count method

var count = mystring.Count(x => x == '$') 
like image 103
gprasant Avatar answered Sep 30 '22 18:09

gprasant


int count = myString.TakeWhile(c => c == '$').Count(); 

And without LINQ

int count = 0; while(count < myString.Length && myString[count] == '$') count++; 
like image 20
Yuriy Faktorovich Avatar answered Sep 30 '22 18:09

Yuriy Faktorovich