我正在使用字符串的替换方法。我有一个字符串数组列表,试图让用户选择一个要从数组中删除的字母和一个要替换为的字母。当我执行程序并在用户选择要替换的字符后,数组保持不变。

有人可以解释为什么会这样吗?

我的数组列表称为“字符串”。我的代码中处理replace函数的部分如下:

public void letter () {

            int b;

            Scanner replaceLetter = new Scanner(System.in);
            System.out.println ("What letter would you like to remove?");
            String badLetter = replaceLetter.next();
            System.out.println ("What letter would you like to add?");
            String newLetter = replaceLetter.next();
            for (b=0; b<strings.size(); b++) {
                    String replaceLetters  = strings.get(b);
                    replaceLetters = replaceLetters.replaceAll(badLetter,newLetter);

            }
            System.out.print(strings);

    }

最佳答案

您要做的只是更新对replaceLetters的引用,而不是替换数组strings中指定索引处的字符串。您应该添加以下行:

strings.set(b, replaceLetters);


到您的for循环的结尾:

 for (b=0; b<strings.size(); b++) {
   String replaceLetters  = strings.get(b);
   replaceLetters = replaceLetters.replaceAll(badLetter,newLetter);
   strings.set(b, replaceLetters);
 }

07-26 04:40