imbondbaby imbondbaby - 2 months ago 8
Java Question

Check if pattern exists in a String

I would like to check if a pattern exists in a String using iteration.

Here is what I have currently but I keep getting false as a result of it.

public static void main(String args[]) {
String pattern = "abc";
String letters = "abcdef";

char[] patternArray = pattern.toCharArray();
char[] lettersArray = letters.toCharArray();

for(int i = patternArray.length - 1; i<= 2; i++){
for(int j = lettersArray.length - 1; j <= 5;j++){
if(patternArray[i] == lettersArray[j]){
System.out.println("true");
} else{
System.out.println("false");
}
}
}
}


Basically I would like to check if
abc
exists in the String
abcdef


Note: I don't want to use regex because is too easy. I am trying to find a solution without it because I am curious how to do it with iteration.

Answer

Why not this:

public static void main(String args[]) {
    String pattern = "abc";
    String letters = "abcdef";

    char[] patternArray = pattern.toCharArray();
    char[] lettersArray = letters.toCharArray();
    boolean matched = false;
    for(int i = 0; i< lettersArray.length-patternArray.length && !matched; i++){
        for(int j = 0; j < patternArray.length;j++){
            if(patternArray[j] == lettersArray[i+j]&&j+1==patternArray.length){
                matched = true;
                System.out.println("true");
            }
            else if(i+1 == lettersArray.length-patternArray.length && j+1 == patternArray.length){
                System.out.println("false");
        }
    }
}