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.
Related posts:


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