Implement strstr

Question: Implement strstr in Java. Find the first instance of a string in another string.

Answer:

public int Search(String haystack, String needle){
    for(int i = 0; i < haystack.length(); i++ ) {
        for(int j = 0; j < needle.length() &&
                        i+j < haystack.length(); j++ ) {
            if(needle.charAt(j) != haystack.charAt(i+j)) {
                break;
            } else if (j == needle.length()-1) {
                return i;
            }
        }
    }
    return -1;
}

Like this question? Follow our feed and tweet it.

Get a free subscription to Oracle magazine published by Oracle Corp.
 Powered by Max Banner Ads 

Related posts:

  1. Combinations of a String
  2. First Non-Repeated Character
  3. Reverse the Order of Words in a String
  4. Permutations of a String
  5. Anagrams in an Array of Strings

One Response

  1. Steffen says:

    Isn’t this simply a String.indexOf(String str)? Which strstr do you mean, the C, PHP, …?

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>