JAVA实现startWord(codingbat)

题目如下

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.

startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"

public String startWord(String str, String word) {
    String x = word.substring(1);
    if (str.startsWith(x, 1)) {
        return str.substring(0, word.length());
    } else {
        return "";
    }
}

此题主要学习使用如下方法。
need to learn how to use startsWith() method.

public boolean startsWith​(String prefix,
int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.
Parameters:
prefix - the prefix.
toffset - where to begin looking in this string.
Returns:
true if the character sequence represented by the argument is a prefix of the substring of this object starting at index toffset; false otherwise.The result is false if toffset is negative or greater than the length of this String object; otherwise the result is the same as the result of the expression
this.substring(toffset).startsWith(prefix)

你可能感兴趣的:(JAVA实现startWord(codingbat))