gpt4 book ai didi

java - 创建两个相同长度的字符串,一个重复另一个的结构,同时一遍又一遍地循环相同的字母

转载 作者:搜寻专家 更新时间:2023-10-31 08:23:00 25 4
gpt4 key购买 nike

我有一个任意字符串 "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;
}

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

最佳答案

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

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();
}

关于java - 创建两个相同长度的字符串,一个重复另一个的结构,同时一遍又一遍地循环相同的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20260689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com