1. Introduction
In this quick tutorial, we’ll demonstrate how to replace a character at a specific index in a String in Java.
We’ll present four implementations of simple methods that take the original String, a character, and the index where we need to replace it.
2. Using a Character Array
Let’s begin with a simple approach, using an array of char.
Here, the idea is to convert the String to char[] and then assign the new char at the given index. Finally, we construct the desired String from that array.
public String replaceCharUsingCharArray(String str, char ch, int index) { char[] chars = str.toCharArray(); chars[index] = ch; return String.valueOf(chars); }
This is a low-level design approach and gives us a lot of flexibility.
3. Using the substring Method
A higher-level approach is to use the substring() method of the String class.
It will create a new String by concatenating the substring of the original String before the index with the new character and substring of the original String after the index:
public String replaceChar(String str, char ch, int index) { return str.substring(0, index) + ch + str.substring(index+1); }
4. Using StringBuilder
We can get the same effect by using StringBuilder. We can replace the character at a specific index using the method setCharAt():
public String replaceChar(String str, char ch, int index) { StringBuilder myString = new StringBuilder(str); myString.setCharAt(index, ch); return myString.toString(); }
However, StringBuilder is not thread-safe. In a multi-threaded environment, multiple threads can access the StringBuilder object simultaneously, and the output it produces can’t be predicted.
5. Using StringBuffer
Using StringBuffer, we can overcome the problem of thread safety as the StringBuffer class is thread-safe. It is a synchronized class, where only one thread can access the String at a time, so the output it produces is predictable:
public String replaceChar(String str, char ch, int index) { StringBuffer myString = new StringBuffer(str); myString.setCharAt(index, ch); return myString.toString(); }
6. Conclusion
In this article, we focused on several ways of replacing a character at a specific index in a String using Java.
String instances are immutable, so we need to create a new string or use StringBuffer and StringBuilder to give us some mutability.
As usual, the complete source code for the above tutorial is available over on GitHub.