在这个程序中,我试图返回一个新字符串,该字符串由添加的新字母和旧字母组成(如果不符合约束条件).我不知道如何修复我的代码,以便正确打印.非常感谢任何帮助或建议!
这里有些例子:
str:"asdfdsdfjsdf",单词:"sdf",c:"q"
应该返回"aqdqjq",我得到"asdqqq"
str:"aaaaaaaa",字:"aaa",c:"w"
应该返回"wwaa",截至目前我的代码只返回"ww"
public static String replaceWordWithLetter(String str, String word, String c)
String result = "";
int index = 0;
while (index < str.length() )
{
String x = str.substring(index, index + word.length() );
if (x.equals(word))
{
x = c;
index = index + word.length();
}
result = result + x;
index++;
}
if (str.length() > index)
{
result = result + str.substring(index, str.length() - index);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)