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

人走茶凉 提交于 2020-12-26 11:05:40

问题


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

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

How would one go about this in Java?


回答1:


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



回答2:


You can use IntStream instead. Code might look something like this:

String[] text = "Lorem oldString dolor sit amet".split("\\s+");

IntStream.range(0, text.length).forEach(i ->
        text[i] = text[i].replace("oldString", "newString"));

System.out.println(Arrays.toString(text));
// [Lorem, newString, dolor, sit, amet]

See also: Replace certain string in array of strings



来源:https://stackoverflow.com/questions/65378006/how-to-replace-a-whole-string-with-another-in-an-array-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!