可能重复:
字符串中出现子字符串
在主题中如何检查一个字符串包含另一个字符串多少次?例子:
s1 "babab"
s2 "bab"
Result : 2
如果我使用 Matcher 它只识别第一次出现:
String s1 = JOptionPane.showInputDialog(" ");
String s2 = JOptionPane.showInputDialog(" ");
Pattern p = Pattern.compile(s2);
Matcher m = p.matcher(s1);
int counter = 0;
while(m.find()){
System.out.println(m.group());
counter++;
}
System.out.println(counter);
我可以这样做,但我想在下面使用 Java 库,例如 Scanner、StringTokenizer、Matcher 等:
String s1 = JOptionPane.showInputDialog(" ");
String s2 = JOptionPane.showInputDialog(" ");
String pom;
int count = 0;
for(int i = 0 ; i< s1.length() ; i++){
if(s1.charAt(i) == s2.charAt(0)){
if(i + s2.length() <= s1.length()){
pom = s1.substring(i,i+s2.length());
if(pom.equals(s2)){
count++;
}
}
}
}
System.out.println(count);