创建两个相同长度的字符串,一个重复另一个结构,同时反复循环相同的字母

use*_*874 5 java

我有一个任意字符串"hello my name is timothy"和另一个任意'关键字'字符串"ham".我想创建一个方法,通过反复重复其字符,同时保留空格,使第二个字符串与第一个字符串的长度相同,结构相同.结果将是:"hamha mh amha mh amhamha.到目前为止,这是我的代码:

    public String makeStringsEqual(String str, String keyword)
{
    if (str.length() > keyword.length())
    {
        for(int i = 0; i < str.length(); i++)
        {
            if (str.charAt(i) != ' ')
            {
                keyword += keyword.charAt(i);
            }
            else
                keyword += " ";
        }

    }
    return keyword;
}
Run Code Online (Sandbox Code Playgroud)

返回前一个示例的代码hamhamha ha ha.我怎样才能解决这个问题?

ays*_*nje 4

首先,不要使用keyword += (string),使用 aStringBuilder更快。

public static String makeStringEqual(String str, String keyword) {
    StringBuilder sb = new StringBuilder("");
    if (str.length() > keyword.length()) {

        int j = 0; // this tells you what is the current index for the keyword
        for(int i=0;i<str.length();i++) {
            if (str.charAt(i) == ' ') {
                sb.append(' ');
            } else {
                sb.append(keyword.charAt(j));

                // when you use up a keyword's character, move on to the next char
                j++;

                // make sure to loop back to the start when you're at the end
                j %= keyword.length();
            }
        }
    }
    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)