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. 
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Vikram
  • 2,042
  • 3
  • 14
  • 15

23 Answers23

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.

Jamey Sharp
  • 8,363
  • 2
  • 29
  • 42
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • 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) – Surajit Biswas Jul 03 '20 at 14:52
96

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","");
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
Thuy
  • 1,493
  • 1
  • 11
  • 11
89

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.

atkretsch
  • 2,367
  • 18
  • 24
  • This works unless the index references the last character of the string. – Alex K Sep 03 '21 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 01 '22 at 16:44
18

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);
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    -1: To address individual character replaceAll is not appropriate. You don't answer the question. – Aubin Nov 14 '12 at 19:52
  • 1
    @Aubin I updated my answer for replacing an individual char, mind reconsidering your downvote? – Óscar López Nov 14 '12 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 '12 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. – Óscar López Nov 14 '12 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 '12 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);
Louis Ferraiolo
  • 409
  • 4
  • 18
Yash
  • 9,250
  • 2
  • 69
  • 74
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();
BlizzaN
  • 99
  • 1
  • 4
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;
}
Darkstarone
  • 4,590
  • 8
  • 37
  • 74
आनंद
  • 2,472
  • 4
  • 21
  • 25
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.
Bob Genom
  • 181
  • 3
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;

    }
Nadav
  • 1,730
  • 16
  • 20
3

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

string= string.replace("*", "");
daydreamer
  • 87,243
  • 191
  • 450
  • 722
1

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

Pankaj
  • 5,132
  • 3
  • 28
  • 37
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.

Farhan Syed
  • 336
  • 3
  • 15
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
Abdul Rizwan
  • 3,904
  • 32
  • 31
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);

    }
}
SanA
  • 119
  • 1
  • 6
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);
}
rmuller
  • 12,062
  • 4
  • 64
  • 92
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. :)

koushick
  • 497
  • 2
  • 8
  • 30
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;
}
ceph3us
  • 7,326
  • 3
  • 36
  • 43
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);
}
Erk
  • 1,159
  • 15
  • 9
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
fabiolimace
  • 972
  • 11
  • 13
-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", "");
}
Lekov
  • 7
  • 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 05 '16 at 17:22