A string contains the number of commas

A [string] contains the number of commas

string str = “1,2,3,4,5,6”;
how to count the number of commas in this string?

method 1:

string str = “1,2,3,4,5,6”;
int count = str.Count(ch => ch == ‘,’);
//count=5

Method 2:

str.Split(’,’).Length-1

Method 3:

string str = “1,2,3,4,5,6”;
int count = str.Length - str.Replace(",", “”).Length;

Method 4:

Regex.Matches(str,@",").Count

Method 5:

str.ToCharArray().Where(x=x.Equals(’,’)).ToArray().length

Leave a Comment

Your email address will not be published. Required fields are marked *