How To Remove a Character in String in Different Ways


1. Overview In this tutorial,  We'll explore how to remove a character from a String . Need to remove only one character even though ...

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.

Guide to Remove a Character in String

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");
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".


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");


"(?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.



About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: How To Remove a Character in String in Different Ways
How To Remove a Character in String in Different Ways
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content