165

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. 
}
4
  • 3
    Can you post real example where you want to do this?
    – Rohit Jain
    Nov 14, 2012 at 19:43
  • You have replace not remove. You may need to write your own.
    – kosa
    Nov 14, 2012 at 19:43
  • You can do it with a couple of substring and indexOf. But that will create a new string object.
    – Rohit Jain
    Nov 14, 2012 at 19:44
  • StringBuilder is a read/write class for manipulating characters. You can create it from a String and use sb.toString() to obtain the resulting String.
    – Aubin
    Nov 14, 2012 at 19:50

23 Answers 23

282

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.

1
  • your answer seems to be not working here... String numbers = "0123456789"; char c = '2'; numbers = numbers.replace(c, Character.MIN_VALUE); I want to replace the ' ' character (empty) Jul 3, 2020 at 14:52
95

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","");
1
  • 16
    it doesn't answer the question how to remove by index.
    – walv
    Oct 22, 2021 at 2:59
90

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.

2
  • This works unless the index references the last character of the string.
    – Alex K
    Sep 3, 2021 at 16:46
  • 1
    @AlexK No, It works fine with the last character. When index is the last character, then index+1 equals the length of the string, and str.substring(str.length) returns an empty string.
    – RoToRa
    Apr 1, 2022 at 16:44
19

No, because Strings in Java are immutable. You'll have to create a new string removing the character you don't want.

For replacing a single char c at index position idx in string str, do something like this, and remember that a new string will be created:

String newstr = str.substring(0, idx) + str.substring(idx + 1);
5
  • 1
    -1: To address individual character replaceAll is not appropriate. You don't answer the question.
    – Aubin
    Nov 14, 2012 at 19:52
  • 1
    @Aubin I updated my answer for replacing an individual char, mind reconsidering your downvote? Nov 14, 2012 at 19:58
  • 1
    To address individual INDEXED character replace() is not appropriate. You don't answer the question (re-read it). I can't downvote again...
    – Aubin
    Nov 14, 2012 at 20:01
  • 1
    @Aubin reread the second part of my answer deals with that case, just as the question asked, now how about removing the downvote? the answer is correct, it just considers one case additional to the one asked in the question. Nov 14, 2012 at 20:06
  • 9
    Your answer is now totally different, you have first replaced "replaceAll()" by "replace()", then replaced "replace()" by "substring()". Now, it's a verbatim copy of atkretsch, which as quickly and correctly answered the question. Your answer doesn't add anything more. Remove it, please.
    – Aubin
    Nov 14, 2012 at 21:43
17
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);
0
9

To modify Strings, read about StringBuilder because it is mutable except for immutable String. Different operations can be found here https://docs.oracle.com/javase/tutorial/java/data/buffers.html. The code snippet below creates a StringBuilder and then append the given String and then delete the first character from the String and then convert it back from StringBuilder to a String.

StringBuilder sb = new StringBuilder();

sb.append(str);
sb.deleteCharAt(0);
str = sb.toString();
8

Consider the following code:

public String removeChar(String str, Integer n) {
    String front = str.substring(0, n);
    String back = str.substring(n+1, str.length());
    return front + back;
}
4

You may also use the (huge) regexp machine.

inputString = inputString.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.
4

If you want to remove a char from a String str at a specific int index:

    public static String removeCharAt(String str, int index) {

        // The part of the String before the index:
        String str1 = str.substring(0,index);

        // The part of the String after the index:            
        String str2 = str.substring(index+1,str.length());

        // These two parts together gives the String without the specified index
        return str1+str2;

    }
3

By the using replace method we can change single character of string.

string= string.replace("*", "");
1

Use replaceFirst function of String class. There are so many variants of replace function that you can use.

0
1

If you need some logical control over character removal, use this

String string = "sdsdsd";
char[] arr = string.toCharArray();
// Run loop or whatever you need
String ss = new String(arr);

If you don't need any such control, you can use what Oscar orBhesh mentioned. They are spot on.

1

Easiest way to remove a char from string

String str="welcome";
str=str.replaceFirst(String.valueOf(str.charAt(2)),"");//'l' will replace with "" 
System.out.println(str);//output: wecome
0
1
public class RemoveCharFromString {
    public static void main(String[] args) {
        String output = remove("Hello", 'l');
        System.out.println(output);
    }

    private static String remove(String input, char c) {

        if (input == null || input.length() <= 1)
            return input;
        char[] inputArray = input.toCharArray();
        char[] outputArray = new char[inputArray.length];
        int outputArrayIndex = 0;
        for (int i = 0; i < inputArray.length; i++) {
            char p = inputArray[i];
            if (p != c) {
                outputArray[outputArrayIndex] = p;
                outputArrayIndex++;
            }

        }
        return new String(outputArray, 0, outputArrayIndex);

    }
}
1

In most use-cases using StringBuilder or substring is a good approach (as already answered). However, for performance critical code, this might be a good alternative.

/**
 * Delete a single character from index position 'start' from the 'target' String.
 * 
 * ````
 * deleteAt("ABC", 0) -> "BC"
 * deleteAt("ABC", 1) -> "B"
 * deleteAt("ABC", 2) -> "C"
 * ````
 */
public static String deleteAt(final String target, final int start) {
    return deleteAt(target, start, start + 1);
} 


/**
 * Delete the characters from index position 'start' to 'end' from the 'target' String.
 * 
 * ````
 * deleteAt("ABC", 0, 1) -> "BC"
 * deleteAt("ABC", 0, 2) -> "C"
 * deleteAt("ABC", 1, 3) -> "A"
 * ````
 */
public static String deleteAt(final String target, final int start, int end) {
    final int targetLen = target.length();
    if (start < 0) {
        throw new IllegalArgumentException("start=" + start);
    }
    if (end > targetLen || end < start) {
        throw new IllegalArgumentException("end=" + end);
    }
    if (start == 0) {
        return end == targetLen ? "" : target.substring(end);
    } else if (end == targetLen) {
        return target.substring(0, start);
    }
    final char[] buffer = new char[targetLen - end + start];
    target.getChars(0, start, buffer, 0);
    target.getChars(end, targetLen, buffer, start);
    return new String(buffer);
}
0
1

*You can delete string value use the StringBuilder and deletecharAt.

String s1 = "aabc";
StringBuilder sb = new StringBuilder(s1);
for(int i=0;i<sb.length();i++)
{
  char temp = sb.charAt(0);
  if(sb.indexOf(temp+"")!=1)
  {                             
    sb.deleteCharAt(sb.indexOf(temp+""));   
  }
}
1

To Remove a Single character from The Given String please find my method hope it will be usefull. i have used str.replaceAll to remove the string but their are many ways to remove a character from a given string but i prefer replaceall method.

Code For Remove Char:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;


public class Removecharacter 
{

    public static void main(String[] args) 
    {
        String result = removeChar("Java", 'a');
        String result1 = removeChar("Edition", 'i');

         System.out.println(result + " " + result1);

    }


    public static String removeChar(String str, char c) {
        if (str == null)
        {
            return null;
        }
        else
        {   
        return str.replaceAll(Character.toString(c), "");
        }
    }


}

Console image :

please find The Attached image of console,

enter image description here

Thanks For Asking. :)

0
public static String removechar(String fromString, Character character) {
    int indexOf = fromString.indexOf(character);
    if(indexOf==-1) 
        return fromString;
    String front = fromString.substring(0, indexOf);
    String back = fromString.substring(indexOf+1, fromString.length());
    return front+back;
}
0
           BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
   String line1=input.readLine();
   String line2=input.readLine();
         char[]  a=line2.toCharArray();
          char[] b=line1.toCharArray();
           loop: for(int t=0;t<a.length;t++) {

            char a1=a[t];
           for(int t1=0;t1<b.length;t1++) {
               char b1=b[t1];  
               if(a1==b1) {
                   StringBuilder sb = new StringBuilder(line1);
                   sb.deleteCharAt(t1);
                   line1=sb.toString();
                   b=line1.toCharArray();
                   list.add(a1);
                   continue  loop;   
               }


            }
0

When I have these kinds of questions I always ask: "what would the Java Gurus do?" :)

And I'd answer that, in this case, by looking at the implementation of String.trim().

Here's an extrapolation of that implementation that allows for more trim characters to be used.

However, note that original trim actually removes all chars that are <= ' ', so you may have to combine this with the original to get the desired result.

String trim(String string, String toTrim) {
    // input checks removed
    if (toTrim.length() == 0)
        return string;

    final char[] trimChars = toTrim.toCharArray();
    Arrays.sort(trimChars);

    int start = 0;
    int end = string.length();

    while (start < end && 
        Arrays.binarySearch(trimChars, string.charAt(start)) >= 0)
        start++;

    while (start < end && 
        Arrays.binarySearch(trimChars, string.charAt(end - 1)) >= 0)
        end--;

    return string.substring(start, end);
}
0
public String missingChar(String str, int n) {
  String front = str.substring(0, n);

// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.

String back = str.substring(n+1, str.length());
  return front + back;
}
0

I just implemented this utility class that removes a char or a group of chars from a String. I think it's fast because doesn't use Regexp. I hope that it helps someone!

package your.package.name;

/**
 * Utility class that removes chars from a String.
 * 
 */
public class RemoveChars {

    public static String remove(String string, String remove) {
        return new String(remove(string.toCharArray(), remove.toCharArray()));
    }

    public static char[] remove(final char[] chars, char[] remove) {

        int count = 0;
        char[] buffer = new char[chars.length];

        for (int i = 0; i < chars.length; i++) {

            boolean include = true;
            for (int j = 0; j < remove.length; j++) {
                if ((chars[i] == remove[j])) {
                    include = false;
                    break;
                }
            }

            if (include) {
                buffer[count++] = chars[i];
            }
        }

        char[] output = new char[count];
        System.arraycopy(buffer, 0, output, 0, count);

        return output;
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
        String remove = "AEIOU";

        System.out.println();
        System.out.println("Remove AEIOU: " + string);
        System.out.println("Result:       " + RemoveChars.remove(string, remove));
    }
}

This is the output:

Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result:       TH QCK BRWN FX JMPS VR TH LZY DG
0
-2

For example if you want to calculate how many a's are there in the String, you can do it like this:

if (string.contains("a"))
{
    numberOf_a++;
    string = string.replaceFirst("a", "");
}
1
  • 2
    This answer doesn't address the question, and it doesn't even work for its stated purpose. It's only going to run the replace operation once.
    – Kenster
    Aug 5, 2016 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.