Java String insert a character at a specific index example shows how to insert a character in the string a specified index using the substring method.
How to insert a character into the string at a specific index?
The String class in Java does not provide any methods using which we can insert a character into it. The reason being is that the String is immutable in Java. In other words, it can not be changed once it is created.
But that does not mean that we can not do that. We can certainly insert a character in a string using the substring
method and get a new string object having a new character sequence.
The String class provides two overloaded versions of the substring
method.
1 |
public String substring(int startIndex) |
This method returns a substring
of the string starting from the start index till the last index.
1 |
public String substring(int startIndex, int endIndex) |
This method returns the substring from a string starting at the startIndex and ending at the endIndex – 1.
We are going to use both of these methods to insert the character in the string as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.javacodeexamples.stringexamples; public class StringInsertCharacter { public static void main(String[] args) { String str = "HelloWorld"; /* * Insert the . at index 5 */ String strNewString = str.substring(0, 5) + "." + str.substring(5); System.out.println(strNewString); } } |
Output
1 |
Hello.World |
As you can see from the code, we took string substring from index 0 to 4 (end index is exclusive), concatenated it with the character we want to insert, and concatenated it again with the string substring from index 5 till the end of the string.
The newer Java runtimes automatically optimize the string concatenation to use the StringBuilder. Though it happens automatically, you can still insert a character in the string at a specified index using the StringBuilder as given below.
1 2 3 4 5 |
String str = "HelloWorld"; String strNewString = new StringBuilder(str).insert(5, ".").toString(); System.out.println(strNewString); |
Output
1 |
Hello.World |
If you want to learn more about string in Java, please visit the Java String Tutorial.
Please let me know your views in the comments section below.