Languages
[Edit]
EN

Java - replace all occurrences of string

0 points
Created by:
Joshua-Heath
535

In this article, we would like to show you how to replace all occurrences of string in Java.

Quick solution:

String text = "ABC ABC ABC";
String replacement = "X";
String result = text.replaceAll("C", replacement);

System.out.println(result);  // ABX ABX ABX

 

1. Practical example using String replaceAll() method

In this example, we use replaceAll() method to replace all occurrences of the "C" in the text string to "X".

public class Example {

    public static void main(String[] args) {
        String text = "ABC ABC ABC";
        String replacement = "X";
        String result = text.replaceAll("C", replacement);

        System.out.println("Original text: " + text);    // ABC ABC ABC
        System.out.println("Modified text: " + result);  // ABX ABX ABX
    }
}

Output:

Original text: ABC ABC ABC
Modified text: ABX ABX ABX

2. Practical example using String replace() method

In this example, we use replace() method to replace all occurrences of the "C" in the text string to "X".

public class Example {

    public static void main(String[] args) {
        String text = "ABC ABC ABC";
        String replacement = "X";
        String result = text.replace("C", replacement);

        System.out.println("Original text: " + text);    // ABC ABC ABC
        System.out.println("Modified text: " + result);  // ABX ABX ABX
    }
}

Output:

Original text: ABC ABC ABC
Modified text: ABX ABX ABX

Note:

The difference between replace() and replaceAll() is insignificant. The replaceAll() method takes regex as the first argument, while replace() takes char or CharSequence.

References

  1. String replace(char oldChar, char newChar) (Java Platform SE 7 )
  2. String replace(CharSequence target, CharSequence replacement) (Java Platform SE 7 )
  3. String replaceAll(String regex, String replacement) (Java Platform SE 7 )

Java - String (popular problems)

Java - replace all occurrences of string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join