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?
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?
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 straightforward, 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 == '&')
Your string example looks like the query string part of a GET. If so, note that HttpContext has some help for you
int numberOfArgs = HttpContext.Current.QueryString.Count;
For more of what you can do with QueryString, see NameValueCollection
Here is the most inefficient way to get the count in all answers. But you'll get a Dictionary that contains key-value pairs as a bonus.
string test = "key1=value1&key2=value2&key3=value3";
var keyValues = Regex.Matches(test, @"([\w\d]+)=([\w\d]+)[&$]*")
.Cast<Match>()
.ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);
var count = keyValues.Count - 1;