public static void main(String [] args)
{
String i = "Hello world Hello";
String test = "Hello";
int count = 0;
int index = 0;
do
{
count ++;
index = i.indexOf(test); //在i中搜索Hello字符
index += test.length(); // 获得下一个开始索引
index = i.indexOf(test, index); //在指定索引处继续往后搜索
}while(index!=-1); //index不等于-1时继续执行上述代码查找字符。
System.out.println(count);
}我的原意是编写一个程序,这个程序计算字符串中Hello字符出现的次数,可是陷入了死循环,怎么都看不出到底是哪里导致的,而且我点击编译运行,机器变得异常的卡,机器配置本来就不高,请看出哪里错误的朋友指出,谢谢~。
{
String i = "Hello world Hello";
String test = "Hello";
int count = 0;
int index = 0;
do
{
count ++;
index = i.indexOf(test); //在i中搜索Hello字符
index += test.length(); // 获得下一个开始索引
index = i.indexOf(test, index); //在指定索引处继续往后搜索
}while(index!=-1); //index不等于-1时继续执行上述代码查找字符。
System.out.println(count);
}我的原意是编写一个程序,这个程序计算字符串中Hello字符出现的次数,可是陷入了死循环,怎么都看不出到底是哪里导致的,而且我点击编译运行,机器变得异常的卡,机器配置本来就不高,请看出哪里错误的朋友指出,谢谢~。
while(index!=-1);
i没有任何处理,所以index = i.indexOf(test, index);永远也不可能是-1的
indexOf在没有找到的时候不是会自动返回-1吗??
楼主可以考虑这个代码 public static void main(String [] args){
String i = "Hello world Hello Hello Hello";
String test = "Hello";
int count = -1;
int index = 0;
do {
count ++;
index = i.indexOf(test);
i = i.substring(index+1);
}while(index!=-1); //index不等于-1时继续执行上述代码查找字符。
System.out.println(count);
}
indexOf在没有找到的时候不是会自动返回-1吗??
问题是你的indexOf的源字符一直都是“Hello world Hello”,木有改变,indexOf方法返回的值当然都是同一个了,当然得死循环