Java program to add characters to the middle of a string:
In this post, we will learn how to add characters to the middle of a string in Java. We will insert characters at a given index of a string.
A String is immutable in Java. We can’t directly modify a string. If we change a string, it creates another string. So, if we are adding characters to the middle of a string, we are actually creating another string by modifying the given string.
There are different ways to add characters to the middle of a string. Let me show you all with examples.
Method 1: Insert character to string by using the StringBuffer class:
StringBuffer has many advantages over String. It is a mutable sequence of characters. It can be modified without creating another StringBuffer. We can also change the length and the content of a StringBuffer.
One more advantage of StringBuffer is that they are thread-safe. We can use one StringBuffer object with multiple threads safely.
We can convert a string to a StringBuffer object and we can also convert a StringBuffer object to string back.
StringBuffer class provides a method called insert, by using which, we can insert a character at any index position for a string. So, we need to:
- Convert a string to StringBuffer.
- Insert the character at the provided index.
- convert the StringBuffer back to string.
That’s it.
StringBuffer’s insert method has different variants, i.e. different overloaded methods. But, since we are only inserting a character to a string, we can use the below method:
public StringBuffer insert(int offset, char c)
Here, offset is the index position in the string to insert the character and c is the character to insert. The offset should be greater than or equal to 0 and less than or equal to the length of the string.
For invalid offset, it throws IndexOutOfBoundsException.
Example program using insert:
Let’s take a look at the below program:
import java.util.Scanner;
public class Main {
private static String insertCharacter(String str, char c, int i) {
StringBuilder sb = new StringBuilder(str);
sb.insert(i, c);
return sb.toString();
}
public static void main(String args[]) {
char c;
int index;
Scanner sc = new Scanner(System.in);
String givenString = "The quick brown fox jumps over the lazy dog";
System.out.println("Enter the character: ");
c = sc.next().charAt(0);
System.out.println("Enter the index position: ");
index = sc.nextInt();
String newString = insertCharacter(givenString, c, index);
System.out.println("Original string: " + givenString);
System.out.println("New string: " + newString);
}
}
In this program,
- insertCharacter method is used to insert a character at an index of a string.
- This method takes one string, one character and the index position as arguments.
- It creates a StringBuilder object from the provided string.
- By using insert, it inserts the character at the index position provided as arguments.
- It converts the StringBuilder to a String and returns it.
- givenString is the original string we are using for this program.
- We are taking the character and index values as inputs from the user. These values are stored in the variables c and index.
- The newly created string, returned by insertCharacter is stored in the String variable newString.
- The last two lines are printing the original and the newly created strings.
If you run this program, it will print outputs as like below:
Enter the character:
!
Enter the index position:
0
Original string: The quick brown fox jumps over the lazy dog
New string: !The quick brown fox jumps over the lazy dog
Enter the character:
*
Enter the index position:
5
Original string: The quick brown fox jumps over the lazy dog
New string: The q*uick brown fox jumps over the lazy dog
Method 2: Insert character to string by using the substring() method:
substring method is an inbuilt method of the String class. This method is used to create a new string which is a substring of another string.
We can use this method to insert a character to a string.
Before showing you how to do that, let me show you the definitions of the substring method:
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
- beginIndex is the index to start the substring.
- endIndex is the index to end the substring.
For the first variant, we are not providing endIndex. So, it will return the string till the end.
Java program to insert character in a string using substring:
Now, let’s use substring() to insert a character to a string at a specific position. We have to break the string in two pieces. Then, we will append both strings with the character by using +.
Below program does that:
import java.util.Scanner;
public class Main {
private static String insertCharacter(String str, char c, int i) {
return str.substring(0, i) + c + str.substring(i);
}
public static void main(String args[]) {
char c;
int index;
Scanner sc = new Scanner(System.in);
String givenString = "The quick brown fox jumps over the lazy dog";
System.out.println("Enter the character: ");
c = sc.next().charAt(0);
System.out.println("Enter the index position: ");
index = sc.nextInt();
String newString = insertCharacter(givenString, c, index);
System.out.println("Original string: " + givenString);
System.out.println("New string: " + newString);
}
}
If you run this program, it will give similar output.
Enter the character:
*
Enter the index position:
5
Original string: The quick brown fox jumps over the lazy dog
New string: The q*uick brown fox jumps over the lazy dog
Disadvantage of using substring:
The second method is not a preferred way to add character to a string. This is because, we are breaking the string in two parts, i.e. we are creating two new strings since string is immutable. We are appending the character to these strings and it creates another string. So, we have to create two intermediate strings to get the final string. If you use this method to append character to a large number of strings, it will cause frequent garbage collection.
You might also like:
- Java program to find special numbers in a range
- Create a Rectangle class in Java and calculate area, perimeter
- Java program to check if a number is special or not
- Java program to find the sum of 0, 1, 1, 2, 3, 5, 8.. or Fibonacci series
- How to find the velocity in Java using user-give values
- Java program to convert a decimal to binary format for a float or double value
- How to add a character to the start and end of a string in Java