asp.net 字符在字符串中出现次数

来源:百度知道 编辑:UC知道 时间:2024/05/10 06:06:40
如:"asdfassasdf"中a出现的次数

string str="asdfassasdf";
int count = str.Length - str.Replace("a", String.Empty).Length;

String original = "asdfassasdf";
Int32 count = 0;
foreach(Char c in original.ToCharArray())
{
if (c=='a') count++;
}

//count即是'a'出现的次数

随手写的,没有编译过,你自己试试

用正则表达式

System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex("a", System.Text.RegularExpressions.RegexOptions.None);
System.Text.RegularExpressions.MatchCollection mc = re.Matches("text");
然后
mc.Length
就可以求出有多次匹配成功,即a的出现次数
此方法,不仅可以求出任意字符在字符串的出现次数,只需装a替换成要查找的字符就可以了。