Jac*_*ck 0 java string while-loop
在这个程序中,我试图返回一个新字符串,该字符串由添加的新字母和旧字母组成(如果不符合约束条件).我不知道如何修复我的代码,以便正确打印.非常感谢任何帮助或建议!
这里有些例子:
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)
你似乎过于复杂了.您可以简单地使用该replace()方法:
public static String replaceWordWithLetter(String str, String word, String c) {
return str.replace(word, c);
}
Run Code Online (Sandbox Code Playgroud)
当被称为:
replaceWordWithLetter("asdfdsdfjsdf", "sdf", "q")
Run Code Online (Sandbox Code Playgroud)
产生输出:
aqdqjq
Run Code Online (Sandbox Code Playgroud)
您当前方法的问题是,如果子字符串不等于word,则您将追加与其中一样多的字符word,然后仅向上移动一个索引.如果你不会替换序列,那么你只需要附加一个字符result.使用a也更有效StringBuilder.如上所述,如果String不能被整除word.length(),则会抛出一个StringIndexOutOfBoundsError.要解决此问题,您可以使用该Math.min()方法确保子字符串不会超出范围.原始方法有修复:
public static String replaceWordWithLetter(String str, String word, String c) {
StringBuilder result = new StringBuilder();
int index = 0;
while (index < str.length() )
{
String x = str.substring(index, Math.min(index + word.length(), str.length()));
if (x.equals(word))
{
result.append(c);
index = index + word.length();
}
//If we aren't replacing, only add one char
else {
result.append(x.charAt(0));
index++;
}
}
if (str.length() > index)
{
result.append(str.substring(index, str.length() - index));
}
return result.toString();
}
Run Code Online (Sandbox Code Playgroud)