C#中怎么在字符串中查询子串的个数

2024-12-13 09:13:15
推荐回答(3个)
回答1:

static int Count(string WithinString, string search)
{
if (string.IsNullOrEmpty(search))
throw new ArgumentNullException("search");
int counter = 0;
int index = WithinString.IndexOf(search,0);
while(index >=0 && index < WithinString.Length)
{
counter++;
index = WithinString.IndexOf(search,index+search.Length);
}
return counter;
}
//这是一个方法,WithinString字符串,search你想查看个数的字符串,counter返回个数

回答2:

楼上的朋友们算法太复杂了

直接把字符串的找度减去字符串中将子串替换为空后的长度一减

代码:

字符串.Length - 字符串.Replace("子串", string.Empty).Length

回答3:

string s = "Hello,world";
Dictionary dic = new Dictionary();

for (int i = 0; i < s.Length; i++)

{
if (dic.ContainsKey(s[i]))

{
int t = dic[s[i]];
dic[s[i]] = ++t;

}
else
{
dic.Add(s[i], 1);
}
}
//输出
foreach (var item in dic)
{
Console.WriteLine("{0}出现了{1}次", item.Key,item.Value);
}