gpt4 book ai didi

java - 一个字符串包含另一个字符串多少次

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:56 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Occurences of substring in a string

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

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);

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com