Java oop:查找字符"a"在字符串"What happend today"中出現(xiàn)的次數(shù)

//構(gòu)建一個(gè)java程序,查找字符"a"在字符串"What happend today"中出現(xiàn)的次數(shù)。
package a;
public class Student{
public static void main(String[] args) {
? ?
String str="What happend today";
int times = searchstr("a", str); //返回2
System.out.println("字符a在字符串What happend today中出現(xiàn)的次數(shù):"+times); /*times就是次數(shù)的意思*/
}
public? static? int? ?searchstr(String key/*要搜索的關(guān)鍵詞*/, String str/*字符串*/) {
int index = 0;//每次的搜索到的下標(biāo)
int count = 0;//計(jì)數(shù)器
while (( index=str.indexOf(key, index)) != -1) {
index = index + key.length()/*關(guān)鍵詞的長度*/;
count++;
}
return count; /*沒void就要寫return,這是規(guī)定*/
? ? ? ??
? ? }
}

標(biāo)簽: