is substring of string
Check if string 2 is a substring of string 1. If so return position of start string
ex: " a b c d e" , " c d e" returns 2
Solution: iterative check
Check for first char of string 2
if found, check string 2. length amount of chars
if all chars match, return position
public int isSubstring(String one, String two){
if (one == null || two == null || two.length() > one.length()) return -1;
if (two.length() == 0) return 0;
//check all possible positions of first char string two
for (int i = 0; i <= (one.length - two.length); i++){
int j = 0;
while (j < two.length() && one.charAt(i + j) == two.charAt(j){
j++;
}
if (j = two.length()) return i;
}
return -1;
}
Last updated
Was this helpful?