小编MOn*_*asz的帖子

一个字符串包含多少次

可能重复:
字符串中子字符串的出现

如在主题中如何检查一个字符串包含另一个字符串的次数?例:

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++;
            } …
Run Code Online (Sandbox Code Playgroud)

java regex string

8
推荐指数
1
解决办法
6646
查看次数

标签 统计

java ×1

regex ×1

string ×1