Gustavo
Gustavo

Reputation: 13

recursive substring search java

I am trying to do a recursive search to check whether a sub string appears in a main string. It will return false if it doesn't exist in it, and it will return true if it does. Im not allowed to use the containcs() method in java

this is what i have tried so far

public boolean myContains(String s1, String s2){
    if(s1 == null || s2 == null)
        return false;
    if(s1.isEmpty() || s2.isEmpty())
        return false;
    //int remain= s2.substring(s1);
    return myContains(s1, s2.substring(1));
}

the call method looks like this

System.out.println( test.myContains("an", "banana"));

Upvotes: 1

Views: 3088

Answers (2)

ozgeneral
ozgeneral

Reputation: 6779

If you are supposed to implement everything yourself this should work too

public boolean myContains(String s1, String s2){
    if(s1 == null || s2 == null)
        return false;
    if(s1.isEmpty() || s2.isEmpty())
        return false;
    if(s1.length() > s2.length())
        return false;

    boolean contains = true;
    for(int i=0; i<s1.length(); i++){
       if(s1.charAt(i)!=s2.charAt(i)){
          contains=false; 
          break;
       }
    }
    if(contains == true){return contains;}
    return myContains(s1, s2.substring(1));
}

Upvotes: 1

vincrichaud
vincrichaud

Reputation: 2208

You have to check if s2 start with s1. If yes return true. If not remove the first char of s2 and redo the test.

I think this is what you've tried. But you missed the block where you check if s2 start with s1 and then return true

public boolean myContains(String s1, String s2){
    if(s1 == null || s2 == null)
        return false;
    if(s1.isEmpty() || s2.isEmpty())
        return false;
    if(s2.startsWith(s1))
        return true;
    return myContains(s1, s2.substring(1));
}

Upvotes: 2

Related Questions