c#判断字符串出现的位置的次数
//定义父字符串
string mainstr = "患者:“大夫,我咳嗽得很重。”" +
" 大夫:“你多大年记?” 患者:“七十五岁。”" +
" 大夫:“二十岁咳嗽吗”患者:“不咳嗽。” " +
" 大夫:“四十岁时咳嗽吗?” " +
" 患者:“也不咳嗽。” " +
" 大夫:“那现在不咳嗽,还要等到什么时咳嗽?”";
//定义子字符串
string str = "咳嗽";
//记录出现字数
int count = 0;
Console.Write("出现的位置分别为:");
//循环判断
while (true)
{
//获取第一个符合子字符串的位置的索引
int index = mainstr.IndexOf(str);
//依次判断
if (index != -1)
{
//截取字符串
mainstr = mainstr.Substring(index + 1);
//计数加1
count++;
Console.Write(index + " ");
}
else
{
break;
}
}
Console.WriteLine("\n" + "一共出现的次数为:" + count);
Console.ReadLine();