In Java, a String is immutable, so its characters cannot be changed directly after the string is created. To replace a character at a specific index, we can either create a new String using substring() or use mutable classes such as StringBuilder and StringBuffer.
- Java String objects are immutable.
- A String cannot be modified directly; replacement creates a new String.
Example
Input:
String = "Geeks Gor Geeks", index = 6, ch = 'F'
Output:Geeks For GeeksInput:
String = "Geeks", index = 0, ch = 'g'
Output:geeks
Methods to Replace Character in a String at Specific Index
There are certain methods to replace characters in String are mentioned below:
1. Using String with substring()
Since String is immutable, we cannot directly modify a character. We can create a new string by combining:
- Characters before the specified index
- Characters after the specified index
public class GFG {
public static void main(String[] args) {
String str = "Geeks Gor Geeks";
int index = 6;
char ch = 'F';
System.out.println("Original String = " + str);
str = str.substring(0, index)
+ ch
+ str.substring(index + 1);
System.out.println("Modified String = " + str);
}
}
Output
Original String = Geeks Gor Geeks Modified String = Geeks For Geeks
2. Using StringBuilder
StringBuilder is a mutable sequence of characters, so a character can be directly replaced using the setCharAt() method.
public class GFG {
public static void main(String[] args) {
String str = "Geeks Gor Geeks";
int index = 6;
char ch = 'F';
System.out.println("Original String = " + str);
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(index, ch);
System.out.println("Modified String = " + sb);
}
}
Output
Original String = Geeks Gor Geeks Modified String = Geeks For Geeks
3. Using StringBuffer
StringBuffer is also mutable and provides the setCharAt() method. Unlike StringBuilder, its methods are synchronized, making it suitable when thread-safe mutable string operations are required.
public class GFG {
public static void main(String[] args) {
String str = "Geeks Gor Geeks";
int index = 6;
char ch = 'F';
System.out.println("Original String = " + str);
StringBuffer sb = new StringBuffer(str);
sb.setCharAt(index, ch);
System.out.println("Modified String = " + sb);
}
}v
Output
Original String = Geeks Gor Geeks Modified String = Geeks For Geeks