Home > database >  I have to print the index where the pattern is found. Like if string = "ABCABCDEABCDEA" an
I have to print the index where the pattern is found. Like if string = "ABCABCDEABCDEA" an

Time:09-24

This is my code that i have written, it is giving wrong output.I have to print the index where the pattern is found. Like if string = "ABCABCDEABCDEA" and pattern = "ABCD", the output will be 4 and 9

Let me discuss it's approach-What i want is if the ith element of the string is equal to the 0th element of the pattern. then go inside the loop, and check till pattern.length. Else continue.

public class Word_check {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String str1="ABCDAFGFGFABCDKLHKHABCD";
    String tocheck="ABCD";
    boolean isfound=false;
    int count=0;
    for(int i=0;i<str1.length();i  ) {
        
        if(str1.charAt(i)==tocheck.charAt(count)){
            
            for(int j=i;j<tocheck.length();j  ) {
            
                if(str1.charAt(j)==tocheck.charAt(count)) {
                    
                    isfound=true;
                }
                else {
                    isfound=false;
                    break;
                }
                count  ;
            }
            if(isfound==true) {
                System.out.println(i 1);
            }
            
        }
        else {
            continue;
        }
        count=0;
    }

}

}

CodePudding user response:

Try this instead -

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String str1="ABCDAFGFGFABCDKLHKHABCD";
    String tocheck="ABCD";
    int lastIndex = str1.indexOf(tocheck);
    while (lastIndex != -1){
        System.out.println(lastIndex);
        lastIndex = str1.indexOf(tocheck, lastIndex   1);
    }
}

From your example I see that you want to print index 1 (in java indexes start from 0, hence the program should print 3 and 8). If that is the case, just do System.out.println(lastIndex 1);

CodePudding user response:

As @Stultuske wrote, use indexOf():

var index = str1.indexOf("ABCD");
while (index >= 0) {
    System.out.println(index);
    index = str1.indexOf("ABCD", index   1);
}
  •  Tags:  
  • java
  • Related