Java oop:统计字符串“我爱我的祖国”中“我”出现的次数

统计字符串“我爱我的祖国”中“我”出现的次数
本期知识点:
searchstr(key/*要搜索字符串中的关键词*/, str/*字符串*/)
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。indexOf() 方法对大小写敏感!如果要检索的字符串值没有出现,则该方法返回 -1。
package b;
public class d{
public static void main(String[] args) {
String str="我爱我的祖国";
int times=searchstr("我", str); //返回2
System.out.println("字符“我”在字符串“我爱我的祖国”中出现的次数:"+times); /*times就是次数的意思*/
}
public static int searchstr(String key/*要搜索的关键词*/, String str/*字符串*/){
int index=0;//每次的搜索到的下标
int count=0;//计数器
while (( index=str.indexOf(key, index))!=-1) {
/*indexOf() 方法对大小写敏感!如果要检索的字符串值没有出现,则该方法返回 -1。-1 表示不存在。个人理解:这里indexOf() 会因为!=-1表示不是不存在(即存在),而while循环“存在要检索的字符串值的次数”*/
index = index + key.length()/*关键词的长度*/;
count++;
}
return count; /*没void就要写return,这是规定*/
}
}
