c# 字串中某個詞出現的次數及索引
阿新 • • 發佈:2019-02-10
字串中某個詞出現的次數主要是考察隊字串方法的使用:
indexof():
有9個過載,具體的請轉到F12檢視詳細內容;
本文使用的是第6個過載:
如果找到該字串,則為從零開始的索引位置;如果未找到該字串,則為 -1
有兩個引數:
string value:
要搜尋的字元
int startIndex:
搜尋的起始位置
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //統計出字串中,下雪出現的次數,並每次出現的索引位置; 6string 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 }
2016-11-1 勿忘我