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

时间:2018-11-20 03:41:27

标签: java string while-loop

在此程序中,我试图返回一个新字符串,该字符串由添加的新字母和不符合约束的旧字母组成。我陷入困境,因为我不知道如何解决我的代码,以便正确打印。任何帮助或建议,我们将不胜感激!

以下是一些示例:

str:“ asdfdsdfjsdf”,单词:“ sdf”,c:“ q”

应返回“ aqdqjq”,我收到“ asdqqq”

str:“ aaaaaaaa”,单词:“ aaa”,c:“ w”

应返回“ wwaa”,截至目前,我的代码仅返回“ wwa”

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

3 个答案:

答案 0 :(得分:6)

您似乎过于复杂了。您可以简单地使用replace()方法:

public static String replaceWordWithLetter(String str, String word, String c)  {
    return str.replace(word, c);
}

哪个叫:

replaceWordWithLetter("asdfdsdfjsdf", "sdf", "q")

产生输出:

aqdqjq

当前方法的问题是,如果子字符串不等于word,则将附加与word中一样多的字符,然后仅向上移动一个索引。如果不替换序列,则只需在result后面附加一个字符。同样,使用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();
}

答案 1 :(得分:0)

使用@GBlodgett的代码找到了解决我的问题的方法:

    String result = "";
    int index = 0;

    while (index <= str.length() - word.length() )
    {
        String x = str.substring(index, index + word.length() );
        if (x.equals(word))
        {
            result = result + c;
            index = index + word.length();
        }
        else {
            result = result + x.charAt(0);
            index++;
        }
    }
    if (str.length() < index + word.length())
    {
        result = result + (str.substring(index));
    }
    return result;
}

答案 2 :(得分:-1)

您可以使用String.replaceAll()方法。 示例:

public class StringReplace {
    public static void main(String[] args) {

        String str = "aaaaaaaa";
        String fnd = "aaa";
        String rep = "w";

        System.out.println(str.replaceAll(fnd, rep));
        System.out.println("asdfdsdfjsdf".replaceAll("sdf", "q"));
    }

}

输出:

wwaa
aqdqjq
相关问题