可能重复:
字符串中子字符串的出现
如在主题中如何检查一个字符串包含另一个字符串的次数?例:
s1 "babab"
s2 "bab"
Result : 2
Run Code Online (Sandbox Code Playgroud)
如果我使用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);
Run Code Online (Sandbox Code Playgroud)
我可以这样做,但我想在下面使用Java库iike 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);
Run Code Online (Sandbox Code Playgroud)
布鲁斯·福特的一些快速解决方案:
String someString = "bababab";
String toLookFor = "bab";
int count = 0;
for (int i = 0; i < someString.length(); i++) {
if (someString.length() - i >= toLookFor.length()) {
if (someString.substring(i, i + toLookFor.length()).equals(toLookFor) && !"".equals(toLookFor)) {
count++;
}
}
}
System.out.println(count);
Run Code Online (Sandbox Code Playgroud)
这会打印出 3。请注意,我假设没有一个Strings 为空。
| 归档时间: |
|
| 查看次数: |
6646 次 |
| 最近记录: |