1

I would like to check whether a string contains a sub list.
For example, str1 = "qwertyuiop" and str2 = "tyu" returns true.
I have written an iterative method.

public static boolean checkString(String str1, String str2) {
    for (int i=0; i<str2.length(); i++) {
        int j = 0;
        for (; j<str1.length()&& str1.charAt(j)!=str2.charAt(i); j++) {

        }
        if (j== str1.length())
            return false;
    }
    return true;    
}

I am trying changing it to recursive method but not sure how as there are two nested for loops. Thank you in advance.

3
  • 1
    Why do not you use str1.contains(str2) method ? Commented Oct 20, 2014 at 4:14
  • 1
    Why not just use String.contains(String seq) ? Commented Oct 20, 2014 at 4:14
  • @sam_eera @Tyler this is just an example of using nested for loop as I want to see how recursion will work when there's more than one loop. Commented Oct 20, 2014 at 4:20

2 Answers 2

3

I suggest you focus on other activities. Java already includes a function to do what you are implementing, and that is String.contains(CharSequence) like

if (str1.contains(str2)) { // <-- wherever you would have called "checkString"
  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

1
public class Test {

    public static void main(String[] args) {
        System.out.println(isSubstring("ankur", "ku"));
    }

    public static boolean isSubstring(String str1, String str2) {
        if ((str1 == null) || (str2 == null) || str1.isEmpty()) {
            return false;
        } else if (str1.startsWith(str2)) {
            return true;
        } else {
            return isSubstring(str1.substring(1), str2);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.