Occurrences of substring in a string

后端 未结 24 1759
眼角桃花
眼角桃花 2020-11-22 03:35

Why is the following algorithm not halting for me? (str is the string I am searching in, findStr is the string I am trying to find)

String str = \"helloslkhe         


        
相关标签:
24条回答
  • 2020-11-22 03:58
    public int indexOf(int ch,
                       int fromIndex)
    

    Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

    So your lastindex value is always 0 and it always finds hello in the string.

    0 讨论(0)
  • 2020-11-22 03:59

    How about using StringUtils.countMatches from Apache Commons Lang?

    String str = "helloslkhellodjladfjhello";
    String findStr = "hello";
    
    System.out.println(StringUtils.countMatches(str, findStr));
    

    That outputs:

    3
    
    0 讨论(0)
  • 2020-11-22 04:01

    try adding lastIndex+=findStr.length() to the end of your loop, otherwise you will end up in an endless loop because once you found the substring, you are trying to find it again and again from the same last position.

    0 讨论(0)
  • 2020-11-22 04:03

    The answer given as correct is no good for counting things like line returns and is far too verbose. Later answers are better but all can be achieved simply with

    str.split(findStr).length
    

    It does not drop trailing matches using the example in the question.

    0 讨论(0)
  • 2020-11-22 04:03

    Here is the advanced version for counting how many times the token occurred in a user entered string:

    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);
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 04:05

    The last line was creating a problem. lastIndex would never be at -1, so there would be an infinite loop. This can be fixed by moving the last line of code into the if block.

    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);
    
    0 讨论(0)
提交回复
热议问题