Java查询字符、字符串出现的次数_java判断字符出现的次数_髮未染霜的博客-CSDN博客
/**
* indexStr("我爱我的字符我的组呼主来","我的");
*
* @param info 原字符
* @param select 检索关键词
*/
public static void indexStr(String info, String select) {
//记录出现的次数
int count = 0;
//从最前方开始检索
int start = 0;
//获取检索字符长度
int index = select.length();
while (true) {
if (info.indexOf(select, start) != -1) {
//找到后次数增加
count++;
//找到对应字符所在索引,当找到后,将下次寻找的位置转换到当前已找到的位置
start = info.indexOf(select, start);
//改变下次检索位置 如:yelloye 从索引0开始查找ye,找到后start = 0;则下次从索引2开始检索(即l处)
start += index; //涉及到多个字符时比 start++检索速度快
} else {
break;
}
}
System.out.println(select + "共出现了:" + count + "次");
}