在应用中通常需要获取一个数组在另一个数组中出现的次数,比如“abc”在“abadsfjiabcjakacnabcdasabc”中出现的次数,可以使用String类中提供的方法进行快捷的实现,实现如下:
//方式一:
public int stringTest1(String str1,String str2){
int length1 = str1.length();//str1的长度
int length2 = str2.length();//str2的长度
int count = 0;//记录出现的次数
int index = 0;//记录出现时的索引
if(length1 < length2){
//判断str1在str2中是否出现
while((index = str2.indexOf(str1)) != -1){
//出现过counter++
count++;
//将str2从index + str1.length 处进行裁剪,然后重新循环
str2 = str2.substring(index + length1);
}
//返回count
return count;
}else{
//如果一次没有出现过,返回0
return 0;
}
}
//方式二:对方式一的改进,方式一中每次循环还需要重新裁剪赋值str2,
//可以使用indexOf(str,index),即从index处开始遍历,这样就不用每
//次循环后进行裁剪数组,可以通过修改index的方法进行循环
public int stringTest2(String str1,String str2){
int length1 = str1.length();
int length2 = str2.length();
int count = 0;
int index = 0;
if(length1 < length2){
while((index = str2.indexOf(str1,index)) != -1){
count++;
//不用重新裁剪字符串,只需要使用indexOf的构造器将index重新赋值
//意思是从index + str.length处继续往后遍历
index += length1;
}
return count;
}else{
return 0;
}
}
进行以上代码的测试:
@Test
public void test1(){
String str1 = "abc";
String str2 = "abcsdfjabcjiadsacbabcabds";
int i = stringTest2(str1, str2);
System.out.println(i);
}