字符串中子字符串的出现


122

为什么以下算法对我来说不停止?(str是我要搜索的字符串,findStr是我要查找的字符串)

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {
    lastIndex = str.indexOf(findStr,lastIndex);

    if( lastIndex != -1)
        count++;

    lastIndex += findStr.length();
}

System.out.println(count);

8
我们在Udacity中做的非常好:我们使用了newSTR = str.replace(findStr,“”); 并返回count =((str.length()-newSTR.length())/ findStr.length());
SolarLunix

字符的类似问题:stackoverflow.com/q/275944/873282
koppor

您是否还不想考虑搜索字符串的前缀为其后缀的情况?在那种情况下,我认为任何建议的答案都行不通。 是一个例子。在那种情况下,您将需要一个更复杂的算法,例如Knuth Morris Pratt(KMP),该算法已在CLRS图书中
Sid

它不停止你的,因为你达到“停止”状态后(lastIndex的== -1),你通过增加lastIndex的值复位(lastIndex的+ = findStr.length();)
Legna

Answers:


83

最后一行造成了问题。lastIndex永远不会为-1,所以会有无限循环。可以通过将最后一行代码移到if块中来解决此问题。

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while(lastIndex != -1){

    lastIndex = str.indexOf(findStr,lastIndex);

    if(lastIndex != -1){
        count ++;
        lastIndex += findStr.length();
    }
}
System.out.println(count);

121
此回复是我一个小时前发布的帖子的准确副本;)
Olivier 2009年

8
请注意,这可能会或可能不会返回预期的结果。使用子字符串“ aa”和搜索“ aaa”的字符串,预期的出现次数可能是一个(此代码返回),但是也可能是两个(在这种情况下,您将需要“ lastIndex ++”而不是“ lastIndex + =” findStr.length()“)取决于您要查找的内容。
Stanislav Kniazev

@olivier没看到...... :( @ @stan绝对正确...我只是在解决问题中的代码...猜测它取决于bobcom在字符串中出现的次数意味着什么...
codebreach

1
人们什么时候应该学习将这种东西包装在静态复制和粘贴方法中?请参阅下面的答案,它也经过了优化。
mmm 2015年

1
这里的道理是,如果您打算编写答案,请首先检查是否有人已经编写了完全相同的答案。相同的答案出现两次实际上没有任何好处,无论您的答案是复制还是单独撰写。
达伍德·伊本·卡里姆

191

如何从Apache Commons Lang 使用StringUtils.countMatches

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

输出:

3

9
不管这个建议多么正确,它都不能接受,因为它没有回答OP的问题
kommradHomer 2014年

3
是不赞成使用的东西还是..我的IDE无法识别
Vamsi Pavan Mahesh 2014年

@VamsiPavanMahesh StringUtils是Apache Commons的一个库。在这里查看:commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/…–
Anup

该答案是彼得·劳瑞(Peter Lawrey)一天前的答案的副本(请参阅下文)。
Zon

StringUtils没有countMatches方法。
格子衬衫

117

lastIndex += findStr.length();被放置在方括号之外,从而导致无限循环(未发现任何情况时,lastIndex始终为findStr.length())。

这是固定版本:

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {

    lastIndex = str.indexOf(findStr, lastIndex);

    if (lastIndex != -1) {
        count++;
        lastIndex += findStr.length();
    }
}
System.out.println(count);

92

较短的版本。;)

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);

8
return haystack.split(Pattern.quote(needle), -1).length - 1;如果,例如needle=":)"
Mr_and_Mrs_D 2012年

2
@lOranger如果没有,,-1它将丢弃结尾的匹配项。
彼得·劳瑞

3
太好了,谢谢!这将教会我阅读Javadoc中的小行...
LaurentGrégoire'12

4
真好!但这只包括不重叠的比赛,不是吗?例如,匹配“ aaa”中的“ aa”将返回1,而不是2?当然,包括重叠或不重叠的匹配都是有效的,并且取决于用户要求(也许一个标志来指示计数重叠,是/否)?
Cornel Masson

2
-1 ..尝试的“AAAA”和“AA”运行这个..正确答案是3不是2
Kalyanaraman Santhanam

79

您真的必须自己处理匹配吗?尤其是如果您只需要出现的次数,则正则表达式会更加简洁:

String str = "helloslkhellodjladfjhello";
Pattern p = Pattern.compile("hello");
Matcher m = p.matcher(str);
int count = 0;
while (m.find()){
    count +=1;
}
System.out.println(count);     

1
:这不找到特殊字符,它会找到0计数低于串 String str = "hel+loslkhel+lodjladfjhel+lo"; Pattern p = Pattern.compile("hel+lo");

13
是的,如果您正确表达您的正则表达式会。尝试使用Pattern.compile("hel\\+lo");+符号在正则表达式中具有特殊含义,需要进行转义。
让(Jean)

4
如果您要获取一个任意String并将其用作与所有特殊正则表达式字符均被忽略的完全匹配的字符串,那么Pattern.quote(str)您是朋友!
Mike Furtak 2015年

2
当str =“ aaaaaa”时,这不适用于“ aaa”。有4个答案,但您给2个答案
Pujan Srivastava

此解决方案不适用于这种情况:str =“这是一个测试\\ n \\ r字符串”,subStr =“ \\ r”,它显示0次。
Maksym Ovsianikov '17

19

我很惊讶没有人提到这一支班轮。它简单,简洁,并且比str.split(target, -1).length-1

public static int count(String str, String target) {
    return (str.length() - str.replace(target, "").length()) / target.length();
}

应该是最佳答案。谢谢!
lakam99

12

这是一个很好的可重用的方法:

public static int count(String text, String find) {
        int index = 0, count = 0, length = find.length();
        while( (index = text.indexOf(find, index)) != -1 ) {                
                index += length; count++;
        }
        return count;
}

8
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
     count++;
     lastIndex += findStr.length() - 1;
}
System.out.println(count);

循环结束时,计数为3;希望能帮助到你


5
该代码包含错误。如果我们搜索单个字符,则findStr.length() - 1返回0,并且我们处于无休止的循环中。
Jan Bodnar 2014年

6

许多给定的答案因以下一项或多项而失败:

  • 任意长度的图案
  • 重叠匹配项(例如,计数“ 23232”中的“ 232”或“ aaa”中的“ aa”)
  • 正则表达式元字符

这是我写的:

static int countMatches(Pattern pattern, String string)
{
    Matcher matcher = pattern.matcher(string);

    int count = 0;
    int pos = 0;
    while (matcher.find(pos))
    {
        count++;
        pos = matcher.start() + 1;
    }

    return count;
}

示例调用:

Pattern pattern = Pattern.compile("232");
int count = countMatches(pattern, "23232"); // Returns 2

如果要进行非正则表达式搜索,只需使用以下LITERAL标记适当地编译模式:

Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
int count = countMatches(pattern, "1+1+1"); // Returns 2

是的,令人惊讶的是,Apache StringUtils中没有这样的东西。
麦克啮齿动物

6
public int countOfOccurrences(String str, String subStr) {
  return (str.length() - str.replaceAll(Pattern.quote(subStr), "").length()) / subStr.length();
}

好答案。您介意添加一些有关其工作原理的注释吗?
santhosh kumar

当然,str-是我们的源字符串,subStr-是一个子字符串。目的是计算str中subStr的出现量。为此,我们使用公式:(ab)/ c,其中a-str的长度,b-没有所有subStr出现的str的长度(为此,我们从str中删除了subStr的所有出现),c-subStr的长度。因此,基本上,我们从str的长度中提取出-没有所有subStr的str的长度,然后将结果除以subStr的长度。如果您还有其他问题,请告诉我。
Maksym Ovsianikov

Santhosh,欢迎您!重要的部分是对SubStr使用Pattern.quote,否则在某些情况下可能会失败,例如:str =“这是一个测试\\ n \\ r字符串”,subStr =“ \\ r”。此处提供的一些类似答案未使用模式,因此在这种情况下它们将失败。
Maksym Ovsianikov '17

没有理由使用regex replace,而不是replaceAll
NateS


3
public int indexOf(int ch,
                   int fromIndex)

返回第一次出现的指定字符在此字符串中的索引,从指定索引开始搜索。

因此,您的lastindex值始终为0,并且始终在字符串中找到问候


2

给出的正确答案不利于计算行返回之类的内容,而且过于冗长。以后的答案比较好,但是所有这些都可以轻松实现

str.split(findStr).length

使用问题中的示例,它不会删除结尾的匹配项。


1
这已经在另一个答案中讨论过了;这个答案也做得更好。
michaelb958--GoFundMonica13年

1
这应该是对有问题的答案的评论,而不是其他答案。
james.garriss 2014年

2

您可以使用内置库函数来出现次数:

import org.springframework.util.StringUtils;
StringUtils.countOccurrencesOf(result, "R-")

1
不起作用,您应该指定使用的依赖项。
塞卡特

1

尝试将其添加lastIndex+=findStr.length()到循环的末尾,否则将陷入无尽的循环,因为一旦找到子字符串,便会尝试从相同的最后位置一次又一次地找到它。


1

试试这个。它将所有匹配项替换为-

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int numberOfMatches = 0;
while (str.contains(findStr)){
    str = str.replaceFirst(findStr, "-");
    numberOfMatches++;
}

而且,如果您不想破坏自己的内容str,则可以创建一个具有相同内容的新字符串:

String str = "helloslkhellodjladfjhello";
String strDestroy = str;
String findStr = "hello";
int numberOfMatches = 0;
while (strDestroy.contains(findStr)){
    strDestroy = strDestroy.replaceFirst(findStr, "-");
    numberOfMatches++;
}

执行此块后,这些将是您的值:

str = "helloslkhellodjladfjhello"
strDestroy = "-slk-djladfj-"
findStr = "hello"
numberOfMatches = 3

1

正如@Mr_and_Mrs_D建议的那样:

String haystack = "hellolovelyworld";
String needle = "lo";
return haystack.split(Pattern.quote(needle), -1).length - 1;

1

基于现有的答案,我想添加一个“较短”的版本,而不要使用if:

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

int count = 0, lastIndex = 0;
while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
    lastIndex += findStr.length() - 1;
    count++;
}

System.out.println(count); // output: 3

如果字符串重复(例如,如果您要在字符串“ xxx”中查找字符串“ xx”),则这一点会考虑在内。
tCoe16年

1

这是用于计算令牌在用户输入的字符串中出现了多少次的高级版本:

public class StringIndexOf {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a sentence please: \n");
        String string = scanner.nextLine();

        int atIndex = 0;
        int count = 0;

        while (atIndex != -1)
        {
            atIndex = string.indexOf("hello", atIndex);

            if(atIndex != -1)
            {
                count++;
                atIndex += 5;
            }
        }

        System.out.println(count);
    }

}

1

下面的方法显示整个字符串重复多少次子字符串。希望对您有用:

    String searchPattern="aaa"; // search string
    String str="aaaaaababaaaaaa"; // whole string
    int searchLength = searchPattern.length(); 
    int totalLength = str.length(); 
    int k = 0;
    for (int i = 0; i < totalLength - searchLength + 1; i++) {
        String subStr = str.substring(i, searchLength + i);
        if (subStr.equals(searchPattern)) {
           k++;
        }

    }

0

这是另一种不使用regexp / patterns / matchers甚至不使用StringUtils的解决方案。

String str = "helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello";
        String findStr = "hello";
        int count =0;
        int findStrLength = findStr.length();
        for(int i=0;i<str.length();i++){
            if(findStr.startsWith(Character.toString(str.charAt(i)))){
                if(str.substring(i).length() >= findStrLength){
                    if(str.substring(i, i+findStrLength).equals(findStr)){
                        count++;
                    }
                }
            }
        }
        System.out.println(count);

0

如果需要原始字符串中每个子字符串的索引,则可以使用indexOf进行如下操作:

 private static List<Integer> getAllIndexesOfSubstringInString(String fullString, String substring) {
    int pointIndex = 0;
    List<Integer> allOccurences = new ArrayList<Integer>();
    while(fullPdfText.indexOf(substring,pointIndex) >= 0){
       allOccurences.add(fullPdfText.indexOf(substring, pointIndex));
       pointIndex = fullPdfText.indexOf(substring, pointIndex) + substring.length();
    }
    return allOccurences;
}

0
public static int getCountSubString(String str , String sub){
int n = 0, m = 0, counter = 0, counterSub = 0;
while(n < str.length()){
  counter = 0;
  m = 0;
  while(m < sub.length() && str.charAt(n) == sub.charAt(m)){
    counter++;
    m++; n++;
  }
  if (counter == sub.length()){
    counterSub++;
    continue;
  }
  else if(counter > 0){
    continue;
  }
  n++;
}

return  counterSub;

}


这个问题已有8年历史了,并且没有任何迹象表明为什么这是比其他22个解决方案更好的解决方案,应该将其删除
Jason Wheeler

0

此解决方案打印整个字符串中给定子字符串出现的总数,还包括确实存在重叠匹配的情况。

class SubstringMatch{
    public static void main(String []args){
        //String str = "aaaaabaabdcaa";
        //String sub = "aa";
        //String str = "caaab";
        //String sub = "aa";
        String str="abababababaabb";
        String sub = "bab";

        int n = str.length();
        int m = sub.length();

        // index=-1 in case of no match, otherwise >=0(first match position)
        int index=str.indexOf(sub), i=index+1, count=(index>=0)?1:0;
        System.out.println(i+" "+index+" "+count);

        // i will traverse up to only (m-n) position
        while(index!=-1 && i<=(n-m)){   
            index=str.substring(i, n).indexOf(sub);
            count=(index>=0)?count+1:count;
            i=i+index+1;  
            System.out.println(i+" "+index);
        }
        System.out.println("count: "+count);
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.