package time_3_30;
/*
获取一个字符串在另一个字符串中出现的次数
*/
public class StringDemo1 {
public static void main(String[] args) {
String str1 = "ab";
String str2 = "abcsabsjabsab";
Times times = new Times();
int a = times.time(str1,str2);
System.out.println(a);
}
}
class Times{
public int time(String str1, String str2){ //字符串str1出现在str2中的次数
int l1 = str1.length()-1;
int l2 = str2.length()-1;
while(l1 >=0 && l2 >=0 && l1 <= l2){ //字符串不为0且字符串str1不大于str2
int t = 0; //设置默认次数为0
for(int i = 0; i <= l2; i++){
for(int j = 0; j <= l1; j++){
if (str1.charAt(j) == str2.charAt(i)){
// System.out.println("j:" + j);
// System.out.println("i:" + i);
if(j == l1){ //当字符串l2时,出现l1子字符串,次数加1,再继续遍历l1
t++;
System.out.println("t:" + t);
j = 0;
}
if(i <= l1){ //防止i索引越界
i++;
}else{break;}
}
}
}
return t;
}
return 0;
}
}
获取一个字符串在另一个字符串中出现的次数 :Java
最新推荐文章于 2024-05-24 15:19:59 发布