0

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

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use IntStream over the indices of this array and process certain strings in a certain way:

String[] text = {"Lorem", "oldString", "dolor", "sit", "amet"};

IntStream.range(0, text.length)
        // to filter the certain strings, or you
        // can skip this line to process each string
        .filter(i -> text[i].equals("oldString"))
        // processing a string
        .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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.