How to remove single character from a String

Solution 1:

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.

Solution 2:

You can use Java String method called replace, which will replace all characters matching the first parameter with the second parameter:

String a = "Cool";
a = a.replace("o","");

Solution 3:

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.

Solution 4:

String str = "M1y java8 Progr5am";

deleteCharAt()

StringBuilder build = new StringBuilder(str);
System.out.println("Pre Builder : " + build);
    build.deleteCharAt(1);  // Shift the positions front.
    build.deleteCharAt(8-1);
    build.deleteCharAt(15-2);
System.out.println("Post Builder : " + build);

replace()

StringBuffer buffer = new StringBuffer(str);
    buffer.replace(1, 2, ""); // Shift the positions front.
    buffer.replace(7, 8, "");
    buffer.replace(13, 14, "");
System.out.println("Buffer : "+buffer);

char[]

char[] c = str.toCharArray();
String new_Str = "";
    for (int i = 0; i < c.length; i++) {
        if (!(i == 1 || i == 8 || i == 15)) 
            new_Str += c[i];
    }
System.out.println("Char Array : "+new_Str);