Java oop:統(tǒng)計(jì)字符串“我愛我的祖國”中“我”出現(xiàn)的次數(shù)

統(tǒng)計(jì)字符串“我愛我的祖國”中“我”出現(xiàn)的次數(shù)
本期知識(shí)點(diǎn):
searchstr(key/*要搜索字符串中的關(guān)鍵詞*/, str/*字符串*/)
indexOf() 方法可返回某個(gè)指定的字符串值在字符串中首次出現(xiàn)的位置。indexOf() 方法對(duì)大小寫敏感!如果要檢索的字符串值沒有出現(xiàn),則該方法返回 -1。
package b;
public class d{
public static void main(String[] args) {
String str="我愛我的祖國";
int times=searchstr("我", str); //返回2
System.out.println("字符“我”在字符串“我愛我的祖國”中出現(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) {
/*indexOf() 方法對(duì)大小寫敏感!如果要檢索的字符串值沒有出現(xiàn),則該方法返回?-1。-1??表示不存在。個(gè)人理解:這里indexOf() 會(huì)因?yàn)?=-1表示不是不存在(即存在),而while循環(huán)“存在要檢索的字符串值的次數(shù)”*/
index = index + key.length()/*關(guān)鍵詞的長度*/;
count++;
}
return count; /*沒void就要寫return,這是規(guī)定*/
? ? ? }
}
