小编Jac*_*ck 的帖子

如何返回字符串,其中所有字符串实例都被另一个字符串替换(Java)

在这个程序中,我试图返回一个新字符串,该字符串由添加的新字母和旧字母组成(如果不符合约束条件).我不知道如何修复我的代码,以便正确打印.非常感谢任何帮助或建议!

这里有些例子:

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)

java string while-loop

0
推荐指数
1
解决办法
87
查看次数

标签 统计

java ×1

string ×1

while-loop ×1