How to remove single character from a String

135

For accessing individual characters of a String in Java, we have String.charAt(2). Is there any inbuilt function to remove an individual character of a String in java?

Something like this:

if(String.charAt(1) == String.charAt(2){
   //I want to remove the individual character at index 2. 
}

This question is tagged with java string

~ Asked on 2012-11-14 19:42:28

The Best Answer is


243

You can also use the StringBuilder class which is mutable.

StringBuilder sb = new StringBuilder(inputString);

It has the method deleteCharAt(), along with many other mutator methods.

Just delete the characters that you need to delete and then get the result as follows:

String resultString = sb.toString();

This avoids creation of unnecessary string objects.

~ Answered on 2012-11-14 19:54:38


77

One possibility:

String result = str.substring(0, index) + str.substring(index+1);

Note that the result is a new String (as well as two intermediate String objects), because Strings in Java are immutable.

~ Answered on 2012-11-14 19:44:42


Most Viewed Questions: