Reputation: 503
I am working one of the problems on codingbat and the problem says: Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1. I can not solve it but found an solution online and the code as shown below. The code works, however, why the code still works when the value is like startWord("h", "ix"). the length of word is 2 and length of str is only 1, why code temp = str.substring(1,m) still works??? will is give a error??
public String startWord(String str, String word) {
int n = str.length();
int m = word.length();
String temp;
if(n>=m){
temp = str.substring(1,m);
if(word.substring(1).equals(temp)){
return str.charAt(0)+temp;
}
}
return "";
}
Upvotes: 1
Views: 136
Reputation: 85266
Something like this you mean?
public String startWord(String str, String word) {
if (str.length() > 0 && word.length() > 0 &&
str.substring(1).startsWith(word.substring(1))) {
return str.substring(0, word.length());
}
return "";
}
Upvotes: 2