c# 字符串中某個詞出現的次數及索引

字符串中某個詞出現的次數主要是考察隊字符串方法的使用:ide

indexof():spa

有9個重載,具體的請轉到F12查看詳細內容;code

本文使用的是第6個重載:blog

若是找到該字符串,則爲從零開始的索引位置;若是未找到該字符串,則爲 -1索引

有兩個參數:字符串

string value:string

要搜索的字符it

int startIndex:event

搜索的起始位置class

 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
相關文章
相關標籤/搜索