我想搜索一个字符串在另一个字符串中出现多少次 当我在末尾放置类似的字符串时,它将无法正常工作。
public class C3_Project3_WPr {
public static void main(String[] args) {
String strn1="AliAliAli";
String strn2="AliAliSinaAli";
String strn3="Ali";
int count1=StringCounter(strn1, strn3);
System.out.println(count1);
int count2=StringCounter(strn2, strn3);
System.out.println(count2);
}
//ُString in String Method
static int StringCounter(String str1, String str2){
int counter=0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for(int i= 0; i<str1.length(); i++){
if(str1.contains(str2)){
counter++;
str1= str1.substring(str2.length());
}
}
return counter;
}
}
答案 0 :(得分:1)
解决问题的方法在这里
public static void main(String[] args) {
String strn1 = "AliAliAliwewdwdweAli";
String strn2 = "AliAliSinaAliAlAli";
String strn3 = "Ali";
int count1 = StringCounter(strn1, strn3);
System.out.println(count1);
int count2 = StringCounter(strn2, strn3);
System.out.println(count2);
}
// ُString in String Method
static int StringCounter(String str1, String str2) {
int counter = 0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for (int i = str1.indexOf(str2); i >= 0; i = str1.indexOf(str2, i + str2.length())) {
counter++;
}
return counter;
}
}
答案 1 :(得分:0)
修改str1
时,您仅考虑了搜索字符串的长度,但忽略了在其中找到索引的索引。解决此问题(例如,使用indexOf
)也可以解决您的结果:
int index = str1.indexOf(str2);
while (index >= 0) {
counter++;
index = str1.indexOf(str2, index + str2.length());
}
答案 2 :(得分:0)
使用递归方法:这是解决问题的快速简便的方法:
static int StringCounter(String str1, String str2){
return (str1.contains(str2)) ? 1 + StringCounter(str1.replaceFirst(str2, ""), str2) : 0;
}