Number of occurrences of a character in a string

dotnet-practitioner picture dotnet-practitioner · May 1, 2012 · Viewed 195.6k times · Source

I am trying to get the number of occurrences of a certain character such as & in the following string.

string test = "key1=value1&key2=value2&key3=value3";

How do I determine that there are 2 ampersands (&) in the above test string variable?

Answer

Michael Frederick picture Michael Frederick · May 1, 2012

You could do this:

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

Or with LINQ:

test.Count(x => x == '&');