1. Overview
In this tutorial, We'll explore how to remove a character from a String. Need to remove only one character even though it is at any position or appears several times.String class has many utility methods that are very useful when working with Strings such as isEmpty(), equals(), contains() and many.
For accessing a character at a specified position, String class has a charAt method. But String api is not having any method to remove a char from String. So, How do we remove from String. We will see different ways to do it. But remember, String is immutable that means once string is created it's content can not be changed. A new string object will be created for every operation done on it.
We will be using string "Jhonny Jhonny Yes Papa" in all our examples in this post.
String string = "Jhonny Jhonny Yes Papa";
2. replace()
Replace() method takes two parameters i.e. oldChar - the old character and newChar - the new character.This method does replace all the occurrences of oldChar with newChar . To remove a character from String, we have to replace the old character with empty space "".
2.1 Example
We are going to replace now char n with "" emtpy space that means removing "n" from input string. See the below example code.String newString = string.replace("n", "");
2.2 Output
See the output after removing char 'n' and replaced with empty space.newString : Jhoy Jhoy Yes Papa
2.3 Removing all spaces
Removing all spaces from string using replace method. We need to pass oldChar as " " and newChar as "".String removeAllSpaces = string.replace(" ", "");
2.4 Output
Observe the output and it has removed all spaces.removeAllSpaces: JhonnyJhonnyYesPapa
All occurances of "n" is removed from input string.
3. substring()
String class has another method substring(). This method returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.3.1 Example
We'll take out char 'o' from second index using substring method. substring method will take the string from startIndex to endIndex-1.First take substring from index 0 to 2 and next substring from 3 to string.length. Now, we have to merge these two strings to get the final desired string with removing char 'o'.
String newSubString = string.substring(0, 2) + string.substring(3, string.length());
3.2 Output
newSubString: Jhnny Jhonny Yes Papa
4. StringBuilder
StringBuilder class is available from jdk 1.5 onwards and this is a mutable class that holds mutable sequence of characters. StringBuilder is not synchronized.StringBuilder has a method deleteCharAt() to remove the character from a specified index.
4.1 Example
In the below example code, we will delete the character 'o' at index 2 (Index starts from 0). Just we need to pass the index to the deleteCharAt method.StringBuilder builder = new StringBuilder("Jhonny Jhonny Yes Papa"); builder.deleteCharAt(2); String builderString = builder.toString();
4.2 Output
Let us have a look at the output, first occurrence of char 'o' is deleted.builderString: Jhnny Jhonny Yes Papa
4.3 Exception
We should deal deleteCharAt method very carefully. If index is more than string length then it will throw runtime exception saying "StringIndexOutOfBoundsException".builder.deleteCharAt(200);
Here length of input string is 22 but passing 200 which is greter than it's length. So, It led to exception. See the below complete exception stack trace.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 200,length 22 at java.base/java.lang.String.checkIndex(String.java:3369) at java.base/java.lang.AbstractStringBuilder.deleteCharAt(AbstractStringBuilder.java:916) at java.base/java.lang.StringBuilder.deleteCharAt(StringBuilder.java:293) at com.java.w3scools.blog.string.getbytes.CharRemovalFromString.main(CharRemovalFromString.java:11)
5. Regular Expression
Regular Expression are very important to reduce the developers work but it may reduce the peformance.5.1 Example
String regexString = string.replaceFirst("(?s)(.{2}).(.*)", "$1$2");
Explanation:
"(?s)" - tells regexp to handle newlines like normal characters (just in case). "(.{2})" - group $1 collecting exactly 2 characters "." - any character at index 2 (to be squeezed out). "(.*)" - group $2 which collects the rest of the inputString. "$1$2" - putting group $1 and group $2 together.
5.2 Output
String after removing second index using regular expression.regexString: Jhnny Jhonny Yes Papa
5.3 Remove Lowecase Letters
Using regular expression, we can remove all the lowercase letters from string.String removeLowecase = string.replaceAll("([a-z])", "");
5.4 Output:
String after removing all lowercase letters from input string.removeLowecase: J J Y P
6. Conclusion
In this article, We've discussed all possible ways to delete a character from String using replace(), StringBuilder, substring() and regular expression calling replaceFirst and replaceAll methods. But usage of regular expression is not suggested to use and recommended only if we could not achive using any other alternative peice of code.All the programs are implemented using JDK 12 in this course.
As usual, all code are described in this tutorial are on GitHub.
No comments:
Post a Comment
Please do not add any spam links in the comments section.