Counting how many times a certain char appears in a string

Counting how many times a certain char appears in a string

Added by Mind Hunter updated on Monday, September 24, 2018

How to Count number of times a certain char appears in a string:

Here is a small snippet which count a certain char in given string.

Method 1:

string test_string="This-is-my-test-string";
int count=test_string.Count(c => c == '-');

Method 2:

int count = test_string.TakeWhile(c => c == '-').Count();				
				

Method 3:

int count = 0;
while(count < test_string.Length && test_string[count] == '$') count++;				
				

Method 4:

int count = Regex.Matches(test_string,"-").Count;				
				

Method 5:

int count = test_string.Split('-').Length - 1;				
				

Method 6:

int count = test_string.Where(c => c == '-').Count()				
				

Method 7:

public static int CharInString(this string text, char c)
{
	int count = 0;
    foreach(char ch in text)
    {
    	if(ch.Equals(c))
        {
        	count++;
        }
	}
	return count;
}				
				

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected