【问题标题】:Find and replace first occurrence of a string in a series of strings in an ArrayList在 ArrayList 中的一系列字符串中查找并替换第一次出现的字符串
【发布时间】:2016-06-27 09:47:58
【问题描述】:

我有一个 ArrayList,其中包含“倒垃圾”、“洗碗”等形式的一系列笔记。我有一个笔记类,它的方法应该找到并替换第一次出现的用户给定的字符串,例如“do”,在每个音符(如果有的话)中,并用用户给定的新字符串替换该字符串。例如:如果我有多个以“do x”开头的音符,则每个音符中的“do”应该变成“do not”。到目前为止,这是我的方法:

public void findAndReplaceFirst(String old, String newWord) {
            for (int i = 0; i < notes.size(); i++) {
                String note = notes.get(i);
                if (note.contains(old)) {
                    int loc = note.indexOf(old);
                    int len = old.length();
                    String temp = note.substring(0, loc ) + note.substring(loc + len, note.length());
                    String newString = temp.substring(0, loc) + newWord + temp.substring(loc, temp.length());
                } else {
                    String newString = note;
                }
            }
        }

但是,当我运行 main 方法时,注释字符串没有改变,我不明白为什么。谁能告诉我我在哪里犯了错误?

【问题讨论】:

    标签: java string arraylist intellij-idea replace


    【解决方案1】:

    字符串保持不变,因为 Java 不允许将变量更改传递给方法。在 Java 中,所有对象都按值传递给方法。您必须从 findAndReplaceFirst 方法返回 newString

    您也可以使用 String 类中定义的replaceFirst 方法:

    public String replaceFirst(String regex, String replacement);
    

    假设你想用一些用户输入替换所有出现的“do”,下面的代码使用Listset(int index, E element)方法替换特定索引处的元素。

    假设notesList&lt;String&gt; 的类型或子类型:

    String userInput = /* get user input */
    
    for (int i = 0, n = notes.length(); i < n; i++) {
        String str = notes.get(i).replaceFirst("do", userInput);
        notes.set(i, str);
    }
    

    【讨论】:

    • 这也可以,但我只是想通了。我必须添加 notes.set(i, newString) 并且字符串在 ArrayList 中被替换。感谢您解释为什么它不起作用。
    【解决方案2】:

    您创建了一个名为newString 的修改后的字符串,但实际上您必须使用set() 将其放回列表中。在 for 循环结束之前,添加 notes.set(i, newString);

    【讨论】:

      猜你喜欢
      • 2016-12-19
      • 2014-03-21
      • 2020-05-22
      • 2011-06-05
      • 2014-07-08
      • 2011-08-25
      • 2016-11-02
      相关资源
      最近更新 更多