c# 字符串中某个词出现的次数及索引

字符串中某个词出现的次数主要是考察队字符串方法的使用:

indexof():

有9个重载,具体的请转到F12查看详细内容;

本文使用的是第6个重载:

如果找到该字符串,则为从零开始的索引位置;如果未找到该字符串,则为 -1

有两个参数:

string value:

要搜索的字符

int startIndex:

搜索的起始位置

 1   class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             //统计出字符串中,下雪出现的次数,并每次出现的索引位置;
 6             string text = "今天下雪了吗,明天不会下雪了吧,什么时候才不下雪啊,我要去上学啊!";
 7             string keyWord = "下雪";
 8             int index = 0;
 9             int count = 0;
10             while ((index=text.IndexOf(keyWord,index))!=-1)
11             {
12                 count++;
13                 Console.WriteLine("第{0}次;索引是{1}",count,index);
14                 index =index+ keyWord.Length;
15             }
16             Console.WriteLine("下雪出现的总次数:{0}",count);
17             Console.ReadKey();
18 
19         }
20     }
View Code
原文地址:https://www.cnblogs.com/zlp520/p/3552400.html