How to replace a whole string with another in an array in Java

后端 未结 2 1037
天涯浪人
天涯浪人 2021-01-27 16:45

I want to replace, say String oldString with String newString in an Array along the lines of:

f         


        
2条回答
  •  不要未来只要你来
    2021-01-27 17:13

    You don't need to use replace() in this case, since you are already checking that text[i] is equal to oldString, which means you are replacing the entire String, which means assignment is sufficient:

    for (int i = 0; i < text.length; i++) {
       if (text[i].equals(oldString)) {
          text[i] = newString;
       }
    }
    

    If, on the other hand, you wanted to replace a sub-string of text[i] which is equal to oldString to newString, you could write:

    for (int i = 0; i < text.length; i++) {
        text[i] = text[i].replace(oldString,newString);
    }
    

提交回复
热议问题