字符串中字符的出现次数

我试图在下面的字符串中获取某个字符(如 &)的出现次数。

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

如何确定在上面的测试字符串变量中有2个 & 符号?

201417 次浏览

Why use regex for that. String implements IEnumerable<char>, so you can just use LINQ.

test.Count(c => c == '&')

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 == '&');

You could do this:

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

Or with LINQ:

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;

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;