While working with strings in Java, you may encounter cases where you need to remove/eliminate certain characters from a string. Unfortunately, the standard String class doesn’t provide a built-in remove() method. However, there is nothing to worry about, because Java supports various other methods that facilitate character removal from a string.
In this write-up, we will demonstrate four different methods of removing or deleting a character(s) from a string in Java.
Removing a Character From a String in Java
Use one of the below-listed methods to remove a specific character from a string:
- Method 1: Using replace()
- Method 2: Using substring()
- Method 3: Using deleteCharAt()
- Method 4: Using delete()
Let’s begin with the replace() method.
Method 1: Using replace()
Java offers several variants of the replace() method. It replaces a character/substring of a string with another character/substring. You can use this method (with a blank space as a replacement) to delete a character(s) from a string. The table below illustrates the description and syntax of different variants of the replace() method:
Method Signature | Method Description |
---|---|
replace(char targetChar, char newChar); | It replaces all the occurrences of “targetChar” with “newChar” and returns a new modified string. |
replace(CharSequence targetStr, CharSequence newStr); | It replaces all the occurrences of the “targetStr” with the “newStr” and returns a new string. Where targetStr represents the target substring and newStr represents a new substring(that will replace the targetStr). |
replaceFirst(String regex, String newStr); | This method replaces only the first occurrence of regex with the newStr. Where regex can be a character, word, or substring(to be replaced). |
replaceAll(String regex, String newStr); | This method replaces all the occurrences of the specified regex with the newStr. |
Warning: You can’t use the first variant for removing/eliminating a character from a string. This is because Java doesn’t support empty character constants. If you try to do so, you will encounter the following error:
Example 1: Removing All Occurrences of a Character From a String
In the following example, we invoke the replace() method on the provided string “inputStr” to replace all occurrences of “e” with an empty string “”:
public class RemoveCharJava {
public static void main(String[] args) {
String inputStr = "Hi Geeks, Welcome to JavaBeat";
System.out.println("The Original String is ==> " + inputStr);
System.out.println("The Modified String is == > " + inputStr.replace("e", ""));
}
}
As expected, the replace() method removes/replaces all the appearances of “e” from the given string:
Example 2: Removing the First Occurrence of a Character From a String
To remove only the first occurrence of a character (and retain the remaining occurrences), use the replaceFirst() method instead of the replace() method:
public class RemoveCharJava {
public static void main(String[] args) {
String inputStr = "Hi Geeks, Welcome to JavaBeat";
System.out.println("The Original String is ==> " + inputStr);
System.out.println("The Modified String is == > " + inputStr.replaceFirst("e", ""));
}
}
The output depicts that the replaceFirst() method only deletes the first occurrence of “e” and the rest of the string remains the same:
Example 3: Removing a Specific Word From a String
Other than only one character, you can also remove a complete word/substring from a string using the replace() method, as shown below:
public class RemoveCharJava {
public static void main(String[] args) {
String inputStr = "Hi Geeks, Welcome to JavaBeat";
System.out.println("The Original String is ==> " + inputStr);
System.out.println("The Modified String is == > " + inputStr.replace("Geeks", ""));
}
}
In the above code, the replace method accepts “Geeks” and “” as its parameters. As a result, it replaces all occurrences of “Geeks” with an empty string “”, as shown below:
Example 4: Removing All Capital Letters From a String
You can also specify a regex in the replace() or replaceAll() method to remove a character from a string (based on some specific pattern/condition). For instance, in the below example, we invoke the replaceAll() method to remove all capital characters from the provided string:
public class RemoveCharJava {
public static void main(String[] args) {
String inputStr = "Hi Geeks, Welcome to JavaBeat";
System.out.println("The Original String is ==> " + inputStr);
System.out.println("The Modified String is == > " + inputStr.replaceAll("([A-Z])", ""));
}
}
The “replaceAll()” method accepts two parameters: a regex “[A-Z]”, and an empty string “”. Consequently, it replaces all the capital characters of the string with the empty string “”, as shown below:
Method 2: Using substring()
The substring() is a public method of the Java String class and is available in two variants. The first one takes only the start index while the other one accepts both the start and end index. The first variant extracts a substring from the start index till the last index of the string. While the second variant extracts a substring between the start and end indices. The below snippet demonstrates both variants of the substring() method:
str.substring(int start_Index);
str.substring(int start_Index, int end_Index);
Where the “str” is a target string from which the desired substring will be extracted.
Example 1: Removing the Last Character From a String Using substring()
In the below code, we invoke the substring() method on the “inputStr” with two parameters to remove its last character:
public class RemoveCharJava {
public static void main(String[] args) {
String inputStr = "Hi Geeks, Welcome to JavaBeat";
System.out.println("The Original String is ==> " + inputStr);
System.out.println("The Modified String is == > " + inputStr.substring(0, inputStr.length()-1));
}
}
In the above code, the substring() method accepts “0” and “inputString.length() – 1” as its arguments. As a result, it extracts a substring from the 0th index to the second last index of the string and eventually removes the last character:
Example 2: Removing the First and Last Characters Using substring()
To remove the first and last characters of a string, simply use the substring() method with “1” and “inputString.length() – 1” as its parameters. The “1” indicates that the substring() method extracts a string from the 1st index, which means the 0th index will be skipped. Similarly, “inputString.length() – 1” means the string’s last index will be skipped:
public class RemoveCharJava {
public static void removeFirstLastChar(String inputStr) {
inputStr = inputStr.substring(1, inputStr.length() - 1);
System.out.print("The Modified String After Removing Characters ==> " + inputStr);
}
public static void main(String args[]) {
String inputStr = "javabeat.net";
System.out.println("The Original String is ==> " + inputStr);
removeFirstLastChar(inputStr);
}
}
Eventually, the substring() method will remove the first and last character from the given string and retrieve a new substring as follows:
Method 3: Using deleteCharAt()
deleteCharAt() is a built-in method of the Java StringBuffer class that accepts an index as an argument and removes a character from the specified index. To invoke this method, use the following signature:
str.deleteCharAt(int targetIndex);
Example 1: Removing a Character From a String Based on Index Number
In the following code, we use the deleteCharAt() method to remove a character located at index 7:
public class RemoveCharJava {
public static void main(String[] args) {
StringBuffer inputStr = new StringBuffer("Hi Geeks, Welcome to JavaBeat");
System.out.println("The Original String is ==> " + inputStr);
System.out.println("The Modified String is == > " + inputStr.deleteCharAt(7));
}
}
The output shows that the desired character has been removed from the given string:
Example 2: Removing the First and Last Characters Using deleteCharAt()
To remove the first and last characters from a string, you must invoke the deleteCharAt() method a couple of times, as shown below:
public class RemoveCharJava {
public static String removeFirstLastChar(String inputStr) {
StringBuilder stringBuild = new StringBuilder(inputStr);
stringBuild.deleteCharAt(0);
stringBuild.deleteCharAt(stringBuild.length() - 1);
return stringBuild.toString();
}
public static void main(String args[]) {
String inputStr = "Welcome to javabeat";
System.out.println("The Original String is ==> " + inputStr);
System.out.print("The Modified String After Removing Characters ==> " + removeFirstLastChar(inputStr));
}
}
In the above code, first, we use the deleteCharAt(0) to remove the string’s first character. In the next line, we use the deleteCharAt(stringBuild.length() – 1) to remove the string’s last character. Finally, we print the original and modified string on the console:
Method 4: Using delete()
The delete() is a built-in method of the Java StringBuffer class that is used to remove one or more characters from a string. It accepts the start and end indexes as parameters and retrieves a substring from the start(inclusive) to the end(exclusive) index. To employ this method in Java, use the following signature:
str.delete(int start_index, int end_index);
Example 1: Removing Character(s) Between Specified Indexes
In the following example, we use the delete() method to remove the characters from index 2 to 7:
public class RemoveCharJava {
public static void main(String[] args) {
String inputStr = "Hi Geeks, Welcome to JavaBeat";
System.out.println("The Original String is ==> " + inputStr);
StringBuffer strBuff = new StringBuffer(inputStr);
System.out.println("The Modified String is == > " + strBuff.delete(2, 8));
}
}
The specified characters have been removed from the input string:
Example 2: Removing First and Last Characters Using delete()
The following code removes the first and last character of the string using the delete() method:
public class RemoveCharJava {
public static String removeFirstLastChar(String inputStr) {
StringBuffer stringBuff = new StringBuffer(inputStr);
stringBuff.delete(0, 1);
stringBuff.delete(inputStr.length() - 1, inputStr.length());
return stringBuff.toString();
}
public static void main(String args[]) {
String inputStr = "Let's Learn Java";
System.out.println("The Original String is ==> " + inputStr);
System.out.print("The Modified String After Removing Characters ==> " + removeFirstLastChar(inputStr));
}
}
In this code, we use the delete() method two times: “delete(0, 1)” and “delete(inputStr.length() – 1, inputStr.length())”. The first delete() removes the first character while the second delete() removes the last character from the given string:
How to Remove the Last Word of a String
Removing the string’s last word is a little bit tricky. To do that, first, you must split all the words of the given string based on whitespaces and store the split strings in an array “strWords”. After this, create a new mutable string “modifiedStr” using StringBuilder. Now, iterate the array from the 0th index to the second-last index, append each split string with whitespace, and store it in the “modifiedStr”. This way the string’s last word will be skipped/removed. Finally, invoke the trim() method on the modifiedStr to remove(if any) the whitespaces from the start and end of the modifiedStr:
public class RemoveCharJava {
public static void main(String[] args) {
String inputStr = "Hi Geeks, Welcome to JavaBeat";
System.out.println("The Original String is ==> " + inputStr);
String[] strWords = inputStr.split("\\s+");
StringBuilder modifiedStr = new StringBuilder();
for (int i = 0; i < strWords.length - 1; i++) {
modifiedStr.append(strWords[i]).append(" ");
}
String trimmedStr = modifiedStr.toString().trim();
System.out.println("The Modified String is == > " + trimmedStr);
}
}
From the output, you can observe that the last word of the string has been removed:
This sums up the implementation of removing characters from a string in Java.
Final Thoughts
To remove a character from a string in Java, you can use built-in methods like replace(), substring(), deleteCharAt(), or delete(). The replace() and substring() come in the standard String class while deleteCharAt() and delete() belong to the StringBuffer class. The replace() and substring() methods have several variants that can be used (according to the requirements) to remove characters from a string. Different examples of all these methods are discussed in this Java post to remove a character from a string.