Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of occurrences of a character in a string [duplicate]

Tags:

c#

regex

linq

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?

like image 399
dotnet-practitioner Avatar asked Apr 30 '12 22:04

dotnet-practitioner


People also ask

How do you find duplicate characters in a string C++?

Algorithm. Define a string and take the string as input form the user. Two loops will be used to find the duplicate characters. Outer loop will be used to select a character and then initialize variable count by 1 its inside the outer loop so that the count is updated to 1 for every new character.


1 Answers

You could do this:

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

Or with LINQ:

test.Count(x => x == '&'); 
like image 165
Michael Frederick Avatar answered Oct 05 '22 23:10

Michael Frederick