黑马程序员技术交流社区
标题:
练习:获取一个字符串在另一个字符串中出现的次数.
[打印本页]
作者:
noiary
时间:
2014-9-19 22:33
标题:
练习:获取一个字符串在另一个字符串中出现的次数.
/*
3.获取一个字符串在另一个字符串中出现的次数.
"abkkcdkkefkkskkgkk";
思路:
通过循环 indexOf 方法,创建计数器count和标记index,
字符串每出现一次:i自增,k = 所在位置 + 1;
*/
public class StringTest {
public static void main(String[] args) {
String str = "abkkcdkkefkkskkgkk";
String key = "kkk";
int count = getCount_3(str,key);
System.out.println(key + "在" + str + "中出现" + count + "次.");
}
/*
方法总结: 总体思路与视频教程相仿,但细节却完全不是一个路线,而且我这个无论
用whlie还是for循环都会出现无限循环,使用do whlie 也是无奈之举.
*/
public static int getCount(String str, String key) {
int count=0,k = key.length(),index = -k;
do {
index = str.indexOf(key,index+k);
System.out.println("index= " + index);
count++;
}
while(index != -1);
return count-1;
}
/*
毕老师视频方法:
*/
public static int getCount_1(String str, String key) {
int count = 0, index = 0;
while((index = str.indexOf(key)) != -1) {
str = str.substring(index+key.length());
count++;
}
return count;
}
/*
看完毕老师视频优化自己方法:
*/
public static int getCount_2(String str, String key) {
int count=0, index = 0;
while(index != -1 && (index = str.indexOf(key,index)) != -1) {
//System.out.println("index= " + index);
index = str.indexOf(key, index + key.length());
count++;
}
return count;
}
/*
总结,其实优化后也没有多简洁,但好在把老师的思路加入到了自己的代码当中. 继续努力!
*/
/*
好吧,继续看完后半部分视频之后,给自己跪了...饶了个大圈子把自己绕晕...
*/
public static int getCount_3(String str,String key) {
int count=0, index = 0;
while((index = str.indexOf(key, index)) != -1) {
System.out.println("index= " + index);
index += key.length();
count++;
}
return count;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2