8

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

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

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

5 回答 5

4

lulz 的一种衬垫解决方案

longStr是输入字符串。findStr是要搜索的字符串。没有假设,除了longStrandfindStr必须不是null而且必须findStr至少有 1 个字符。

longStr.length() - longStr.replaceAll(Pattern.quote(findStr.substring(0,1)) + "(?=" + Pattern.quote(findStr.substring(1)) + ")", "").length()

由于两个匹配项只要从不同的索引开始就被认为是不同的,并且可能发生重叠,因此我们需要一种方法来区分匹配项并允许匹配的部分重叠。

诀窍是只使用搜索字符串的第一个字符,并使用前瞻来断言搜索字符串的其余部分。这允许重新匹配重叠部分,并且通过删除匹配的第一个字符,我们可以计算匹配的数量。

于 2012-12-19T13:45:05.863 回答
2

我认为如果您知道在字符串中要查找的单词,这可能会起作用,您可能需要编辑正则表达式模式。

String string = "hellohellohellohellohellohello";
Pattern pattern = Pattern.compile("hello"); 
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find()) count++;
于 2012-12-19T13:38:07.473 回答
1

Matcher类有两个方法“ start ”和“ end ”,它们返回最后一个匹配的开始索引和结束索引。此外,find方法有一个可选参数“start”,从该参数开始搜索。

于 2012-12-19T13:37:22.163 回答
1

你可以这样做

private int counterString(String s,String search) {
    int times = 0;
    int index = s.indexOf(search,0);
    while(index > 0) {
        index = s.indexOf(search,index+1);
        ++times;
    }
    return times;
 }
于 2012-12-19T13:41:02.160 回答
0

一些快速的 Bruce Forte 解决方案:

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

这会打印出 3。请注意,我假设没有一个Strings 为空。

于 2012-12-19T13:36:46.377 回答