The Complete Guide to Java String Replace
Tags: java, tutorial
Published: 2021-03-01 09:48:23

[A colleague of mine Vikram Aruchamy over at LightRun] (https://lightrun.com/java/the-complete-guide-to-java-string-replace/) wrote an excellent, concise, and easy-to-use tutorial on using the `String.Replace()` functionality in Java. I asked his permission to post his article here, and he graciously agreed. His post is a great resource to make sure you understand the utility behind these Java functionalities including examples.

One of the most commonly used functionalities for String objects in Java is String replace. With `replace()`, you can replace an occurrence of a `Character` or `String` literal with another `Character` or `String` literal.

You might use the `String.replace()` method in situations like:

- Replacing special characters in a String (eg, a `String` with the German character ö can be replaced with oe). This won’t change the meaning of the word, but it will help make the string more universally understood.
- Reading data from a CSV file with comma-separated values. The delimiters can be replaced with a space using the replace method to split the words.
- Handling URLs in Java. You may need to encode the string to replace special characters (eg, a space needs to be replaced with _%20_).

In Java, keep in mind that `String` objects are immutable, which means the object cannot be changed once it’s created. `StringBuffer` and `StringBuilder` objects, on the other hand, are mutable, meaning they can be changed after they’re created. So, in some situations, `String.replace()` might not be the best way to replace a character in a string.

In this tutorial, you’ll learn:

- How `String.replace()`, `StringBuilder.replace()`, `StringBuffer.replace()` can be used to replace a specific character or a substring in a `String` and when to use each of them.
What happens to the immutable `String` object when `replace()` or `replaceAll()` is used.
- How `String.replaceAll()` can replace all occurrences of a specific character or a substring in a String.

## Using String.replace()
`String.replace()` is used to replace all occurrences of a specific character or substring in a given `String` object without using regex. There are two overloaded methods available in Java for `replace()`: String.replace() with Character, and String.replace() with CharSequence.

### String.replace() with Character
This method accepts the `oldChar` and `newChar`, then replaces all the `oldChar` in the given string literal with the `newChar` and returns a resultant `String` object.

`public String replace(char oldChar, char newChar)`
![Visual example of how the public String replace function works](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gbkczbb0n546pegw79fn.png)

### String.replace() with CharSequence
[This method]
(https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-java.lang.CharSequence-java.lang.CharSequence-) accepts the target CharSequence and the replacement CharSequence, then replaces all the target CharSequence with the `replacement` CharSequence and returns a resultant `String` object.

[CharSequence](https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html) is an [interface](https://www.w3schools.com/java/java_interface.asp) in Java implemented by `String, StringBuffer, and StringBuilder`. You can use any of these implementations in place of CharSequence.

`public String replace(CharSequence target, CharSequence replacement)`
While the signatures are different, these two implementations of the `replace()` method work much the same way.

## String.replace() Examples
Let’s use the `replace()` method with the `Char` types parameter to replace a single character. You’ll use only single quotes in the `replace()` method parameters to denote `oldChar` and `newChar` as `Characters`. Double quotes make the parameters a String.
```
/** * Method to demonstrate the Replace method using the Chars type parameter */
private static void useStringReplaceWithChar() {
  String sourceString = "The world is schön. This is a String with special Character ö";
  String replacedString = sourceString.replace('ö', 'o');
  System.out.println("Source String before replace : " + sourceString + "\n");
  System.out.println("Replaced String : " + replacedString + "\n");
  System.out.println("Source String after replace : " + sourceString);
}
```
When you execute the program above, you’ll see this output:
```
Source String before replace : The world is schön. This is a String with special Character ö 
Replaced String : The world is schon. This is a String with special Character o 
Source String after replace : The world is schön. This is a String with special Character ö
```
A few things to note:

1. The first line printed the source String with the special character **ö**
2. When we used the `replace()` method, all occurrences of the special character **ö** are replaced with **o**.
3. With the `replace()` method, the original String is not modified. It always returns a new String object.

If you use the `replace()` method with `CharSequence` type parameters (denoted by double quotes instead of single):
```
... 
String replacedString = sourceString.replace("ö", "oe"); 
...
```
You’ll see similar output and the unmodified original String:
```
Source String before replace : The world is schön. This is a String with special Character ö 
Replaced String : The world is schoen. This is a String with special Character oe 
Source String after replace : The world is schön. This is a String with special Character ö
```
You can also use the `replace()` method with the `StringBuilder` implementation in place of `CharSequence` types”:
```
...
StringBuilder sourceStrBuilder = new StringBuilder("ö");
StringBuilder targetStrBuilder = new StringBuilder("oe");
String replacedString = sourceString.replace(sourceStrBuilder, targetStrBuilder);
...
```
When you execute this variation, you’ll see the same output as the previous example.

While the `replace()` method might be the obvious choice for most string replacement operations, it’s not the only option. In the next section, I’ll introduce the `replace()` method in `StringBuilder`.

## Using StringBuilder.replace()
[StringBuilder]
(https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html) is a mutable sequence of characters. It is not thread-safe; methods are not synchronized. It’ll replace the substring sequence in the range passed as index parameters with the replacement String.

This is the method to use if you want to **perform the replace operation in a single-threaded Java program.** You can also use it in multiple thread programs as well, but that’s not recommended because the [methods are not synchronized](https://proandroiddev.com/synchronization-and-thread-safety-techniques-in-java-and-kotlin-f63506370e6d).

First, create a `StringBuilder` initialized with a `String` with the special character **ö**, using the following:
```
String sourceString = "The world is schön. This is a String with special Character ö";
StringBuilder builder = new StringBuilder(sourceString);
```
Next, use the `replace()` method with `StringBuilder`.

The `replace()` method accepts three parameters: `startIndex`, `endIndex`, and the `replacementString`.

- `startIndex` is the beginning index of the replacement in a String literal. It’s inclusive, which means if you specify 1, the index 1 of the String will be included in the replacement.
- `endIndex` is the ending index of the replacement in a String literal. It’s exclusive, which means if you specify 5, the index 5 of the String will not be included in the replacement. Replacements are made only through index 4.
- `replacementString` is the actual replacement String. The specified index range in the String literal will be replaced with this String.
The index of the character to be replaced is a required parameter, but you can use the `StringBuilder.indexOf()` method to identify the index of the special character as shown here:
```
int indexOfUmlauts = builder.indexOf("ö");
```
Now you have the index of the special characters in the `int`, which can be passed to the replace method. The following example shows the full Java code for using the `StringBuilder.replace()`:
```
/** * Demonstrating the Replace method available in StringBuilder */
private static void useStringBuilderReplace() {
  String sourceString = "The world is schön. This is a String with special Character ö";
  StringBuilder builder = new StringBuilder(sourceString);
  int indexOfUmlauts = builder.indexOf("ö");
  System.out.println("Source String before replace : " + sourceString + "\n");
  System.out.println("Using StringBuilder.replace() " + builder.replace(indexOfUmlauts, indexOfUmlauts + 1, "oe") + "\n");
  System.out.println("String builder after replace : " + builder);
}
```
When you execute the above code, you’ll see this output:
```
Source String before replace : The world is schön. This is a String with special Character ö 
Using StringBuilder.replace() : The world is schoen. This is a String with special Character ö 
String builder after replace : The world is schoen. This is a String with special Character ö
```
A few things to note:

1. The first line printed the source String with the special String literal **ö**.
2. When the `StringBuilder.replace()` method is used, only the characters specified in the `startIndex` and `endIndex` are replaced with **o**. It doesn’t replace all the occurrences. You can see the character **ö** at the end is not replaced.
3. When the `StringBuilder.replace()` method is used, the original `StringBuilder` is modified. This is because `StringBuilder` is mutable, and it’s changed directly.

Mutability might be desired in some cases, but be careful. It could be an unintended side effect.

## Using StringBuffer.replace()
[StringBuffer]
(https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html) is a mutable sequence of characters. Similar to `StringBuilder.replace()`, It’ll replace the substring sequence in the range passed as index parameters with the replacement String, but it’s thread-safe. Use this method when you want to perform the replace operation in a multi-threaded Java program.

To begin, create a StringBuffer initialized with a String with the special character **ö** similar to how you did with StringBuilder above:
```
String sourceString = "The world is schön. This is a String with special Character ö";
StringBuffer buffer = new StringBuffer(sourceString);
The replace() method accepts three parameters:
```
- `startIndex` is the beginning index of the replacement in a String literal. It’s inclusive, which means if you specify 1, the index 1 of the String will be included in the replacement.
- `endIndex` is the ending index of the replacement in a String literal. It’s exclusive, which means if you specify 5, the index 5 of the String will not be included in the replacement. Replacements are made only through index 4.
- `replacementString` – The actual replacement String. The specified index range in the String literal will be replaced with this String.

The index of the Character to be replaced is a required parameter, so you can use the `indexOf()` method to find it. The following example shows the full Java code to use the `StringBuffer.replace()`:
```
/** * Demonstrating the Replace method available in StringBuffer */
private static void useStringBufferReplace() {
  String sourceString = "The world is schön. This is a String with special Character ö";
  StringBuffer buffer = new StringBuffer(sourceString);
  int indexOfUmlauts = buffer.indexOf("ö");
  System.out.println("Source String before replace : " + sourceString + "\n");
  System.out.println("Using StringBuffer.replace() " + buffer.replace(indexOfUmlauts, indexOfUmlauts + 1, "oe") + "\n");
  System.out.println("String buffer after replace : " + buffer);
}
```
Just like in the StringBuilder case above, StringBuffer.replace() does _not_ replace all instances of the special character and it _does_ mutate the original string buffer:
```
Source String before replace : The world is schön. This is a String with special Character ö 
Using StringBuffer.replace() The world is schoen. This is a String with special Character ö 
String buffer after replace : The world is schoen. This is a String with special Character ö
```
## Using String.replaceAll()

The last method for replacing strings in Java that I’ll cover is [the `String.replaceAll()` method](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29). It uses a regular expression to check if a matching substring needs replaced. The signature of the `String.replace()` method is shown here:
```
public String replaceAll(String regex, String replacementString)
```
Where:

- `regex` is the regular expression to be matched to find the substring.
- `replacementString` is the String that will replace the matched substring.
## The Difference Between String.replaceAll() and String.replace()
Based on the name alone, you might guess that `replaceAll()` will replace all occurrences of a character or a substring, and you’d be correct, but `String.replace()` also replaces all occurrences of a character or a substring.

The only difference between the two is that **with replaceAll(), you can use a regular expression to match the substring that needs to be replaced, whereas with replace(), you _cannot_ use a regex**. It accepts only `Character` or `CharSequence`.

Therefore, use `replaceAll()` when you don’t know the exact substring to be replaced but you can find it using a regular [expression](https://www.w3schools.com/java/java_regex.asp).

For example, you may get an HTML String response when you consume a RESTful service from your Java program. Within the HTML, you may want to extract only the text and ignore all the HTML tags.

The following example demonstrates how to use `replaceAll()` with a regex to remove all the HTML tags from the response:
```
/** * Demonstrating the replaceAll method using a regular expression */
private static void userStringReplaceAll() {
  String sourceString = "<body><h1>this is heading1</h1></body>";
  String replacedString = sourceString.replaceAll("<(.|\n)+?>", "");
  System.out.println("Source String before replace : " + sourceString + "\n");
  System.out.println("Text without HTMl Tags : " + replacedString + "\n");
  System.out.println("Source String after replace : " + sourceString);
}
```
If you’re not familiar with regex syntax, learn [how to generate it here](https://www.javatpoint.com/java-regex).

When you execute the program above, you’ll see the following output:
```
Source String before replace : <body><h1>this is heading1</h1></body> 
Text without HTML tags : this is heading1 
Source String after replace : <body><h1>this is heading1</h1></body>
```
As you can see, the original string was not modified, but the replaced string has all the tags stripped away. Regex is very useful when you have complicated string replacement rules, so `replaceAll()` will be a good method to keep in your toolbox.

##Conclusion
In this tutorial, you learned how to use the `String.replace()`, `StringBuilder.replace()`, and `StringBuffer.replace()` methods to replace all occurrences of a substring. You also learned which `Char` implementation should be used in case of a single-threaded or multi-threaded Java program, and how to use `replaceAll()` with a regular expression.

If you’re having trouble which string replacement method to use or you have your own suggestions, feel free to leave them in the comments. I look forward to hearing what you think.