Occurrences of substring in a string

后端 未结 24 1890
眼角桃花
眼角桃花 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 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);
        }
    
    }
    

提交回复
热议问题