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)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。