Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackOverflow when checking if one string is contained in another

I currently have a method that is supposed to take two strings and then check if one string exists as a substring in other. It doesn't check both ways so the way in which I pass my strings to the method determines what string is looked for in the other.

Currently I am getting a stackoverflow error.

public boolean checkMatch(String text, String regex, int i){

    int regexL = regex.length();

        if(i == regexL){
            return true;
        }   

        System.out.println(text.charAt(i) + " " + regex.charAt(i));

        if(text.charAt(i) == regex.charAt(i)){
            return checkMatch(text, regex, i++);
        }
        else if(text.charAt(i) != regex.charAt(i)){

            if(text.substring(1) == ""){
                return false;
            }               
            else if(text.substring(1) != ""){
                return checkMatch(text.substring(1), regex, 0);
            }
        }
        return false;

}

I am running a test using my first name as an example.

@Test public void test_52() {
    assertEquals(true, checkMatch("Samual", "mu", 0));
}

the console looks like this after it overflows.

S m

a m

m m

m m

m m

etc

Where am I going wrong? Am I iterating wrong? The stack trace shows that it seems to be getting caught on this line.

return checkMatch(text, regex, i++);

But the defect point is rarely the point of failure. Sorry for the wall of text and code.

like image 946
SHolmes Avatar asked Dec 15 '22 00:12

SHolmes


1 Answers

I don't know if the rest is correct, but here is one error: i++increments i after it was evaluated. You call your function with the same value every time. You probably mean ++i.

like image 187
Drunix Avatar answered Feb 22 '23 23:02

Drunix