Occurrences of substring in a string

后端 未结 24 1856
眼角桃花
眼角桃花 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:40

    This solution prints the total number of occurrence of a given substring throughout the string, also includes the cases where overlapping matches do exist.

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

提交回复
热议问题