Number of occurrences of a character in a string [duplicate]
You could do this:
int count = test.Split('&').Length - 1;
Or with LINQ:
test.Count(x => x == '&');
Because LINQ
can do everything...:
string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();
Or if you like, you can use the Count
overload that takes a predicate :
var count = test.Count(x => x == '&');
The most straight forward, and most efficient, would be to simply loop through the characters in the string:
int cnt = 0;
foreach (char c in test) {
if (c == '&') cnt++;
}
You can use Linq extensions to make a simpler, and almost as efficient version. There is a bit more overhead, but it's still surprisingly close to the loop in performance:
int cnt = test.Count(c => c == '&');
Then there is the old Replace
trick, however that is better suited for languages where looping is awkward (SQL) or slow (VBScript):
int cnt = test.Length - test.Replace("&", "").Length;
Why use regex for that. String
implements IEnumerable<char>
, so you can just use LINQ.
test.Count(c => c == '&')