Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

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

5. 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 StringBuilder to give us some mutability.

As usual, the complete source code for the above tutorial is available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!