Delete char at position in string
Categories:
Deleting a Character at a Specific Position in a Java String

Learn various techniques to remove a character from a Java String at a given index, exploring methods like substring manipulation, StringBuilder, and regular expressions.
Java String
objects are immutable, meaning their content cannot be changed after creation. This characteristic is fundamental to understanding how to 'delete' a character. When you perform an operation that seems to modify a string, you are actually creating a new string with the desired changes. This article will guide you through several common and efficient ways to achieve this, focusing on clarity and performance considerations.
Understanding String Immutability
Before diving into solutions, it's crucial to grasp the concept of string immutability in Java. When you declare a String
variable, it points to a sequence of characters in memory. Any operation that appears to alter this string, such as replace()
or substring()
, doesn't modify the original object. Instead, it returns a brand new String
object containing the result of the operation. The original string remains untouched in the String Pool (if interned) or on the heap, potentially becoming eligible for garbage collection if no longer referenced.
flowchart TD A[Original String] --> B{Operation (e.g., delete char)} B --> C[New String Created] A --(remains)--> A C --(returned)--> D[Reference to New String] A --(no longer referenced)--> E[Garbage Collection (if applicable)]
Flowchart illustrating Java String immutability during modification operations.
Method 1: Using substring()
Concatenation
One of the most straightforward ways to 'delete' a character is by splitting the original string into two parts around the character's position and then concatenating those parts. You take the substring from the beginning up to the character's index and then the substring from the character's index + 1 to the end of the string.
public class StringDelete {
public static String deleteCharUsingSubstring(String str, int position) {
if (str == null || position < 0 || position >= str.length()) {
throw new IllegalArgumentException("Invalid string or position");
}
return str.substring(0, position) + str.substring(position + 1);
}
public static void main(String[] args) {
String original = "Hello World";
int indexToDelete = 6; // 'W'
String modified = deleteCharUsingSubstring(original, indexToDelete);
System.out.println("Original: " + original);
System.out.println("Modified: " + modified);
indexToDelete = 0; // 'H'
modified = deleteCharUsingSubstring(original, indexToDelete);
System.out.println("Modified (first char): " + modified);
indexToDelete = original.length() - 1; // 'd'
modified = deleteCharUsingSubstring(original, indexToDelete);
System.out.println("Modified (last char): " + modified);
}
}
Java code demonstrating character deletion using substring()
and concatenation.
StringBuilder
or StringBuffer
are usually more performant due to their mutable nature.Method 2: Using StringBuilder
or StringBuffer
For scenarios involving frequent string modifications, StringBuilder
(or StringBuffer
for thread-safe operations) is the preferred choice. These classes provide mutable sequences of characters, allowing you to perform operations like deleteCharAt()
directly without creating new objects for each change. Once all modifications are done, you can convert the StringBuilder
back to a String
using its toString()
method.
public class StringBuilderDelete {
public static String deleteCharUsingStringBuilder(String str, int position) {
if (str == null || position < 0 || position >= str.length()) {
throw new IllegalArgumentException("Invalid string or position");
}
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(position);
return sb.toString();
}
public static void main(String[] args) {
String original = "Programming";
int indexToDelete = 3; // 'g'
String modified = deleteCharUsingStringBuilder(original, indexToDelete);
System.out.println("Original: " + original);
System.out.println("Modified: " + modified);
indexToDelete = 0; // 'P'
modified = deleteCharUsingStringBuilder(original, indexToDelete);
System.out.println("Modified (first char): " + modified);
indexToDelete = original.length() - 1; // 'g'
modified = deleteCharUsingStringBuilder(original, indexToDelete);
System.out.println("Modified (last char): " + modified);
}
}
Java code demonstrating character deletion using StringBuilder.deleteCharAt()
.
StringBuilder
is generally faster than StringBuffer
because it is not synchronized. Use StringBuffer
only when thread safety is a strict requirement.Method 3: Converting to Character Array
Another approach involves converting the String
to a char[]
array, creating a new array without the character at the specified position, and then converting it back to a String
. This method can be useful for understanding the underlying character manipulation, though StringBuilder
is often more concise for this specific task.
import java.util.Arrays;
public class CharArrayDelete {
public static String deleteCharUsingCharArray(String str, int position) {
if (str == null || position < 0 || position >= str.length()) {
throw new IllegalArgumentException("Invalid string or position");
}
char[] originalChars = str.toCharArray();
char[] newChars = new char[originalChars.length - 1];
System.arraycopy(originalChars, 0, newChars, 0, position);
System.arraycopy(originalChars, position + 1, newChars, position, originalChars.length - position - 1);
return new String(newChars);
}
public static void main(String[] args) {
String original = "Java Programming";
int indexToDelete = 4; // ' '
String modified = deleteCharUsingCharArray(original, indexToDelete);
System.out.println("Original: " + original);
System.out.println("Modified: " + modified);
}
}
Java code demonstrating character deletion by converting to a character array.