How to remove single character from a String

JavaString

Java Problem Overview


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. 
}

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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;
}

Solution 7 - Java

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

Solution 8 - Java

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.

Solution 9 - Java

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

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

Solution 10 - Java

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;

    }
  

Solution 11 - Java

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

Solution 12 - Java

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.

Solution 13 - Java

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

Solution 14 - Java

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

	}
}

Solution 15 - Java

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

Solution 16 - Java

*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+""));	
  }
}

Solution 17 - Java

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. :)

Solution 18 - Java

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;
}

Solution 19 - Java

           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;   
			   }
			  
			 
			}

Solution 20 - Java

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

Solution 21 - Java

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;
}

Solution 22 - Java

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

Solution 23 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVikramView Question on Stackoverflow
Solution 1 - JavaBhesh GurungView Answer on Stackoverflow
Solution 2 - JavaThuyView Answer on Stackoverflow
Solution 3 - JavaatkretschView Answer on Stackoverflow
Solution 4 - JavaYashView Answer on Stackoverflow
Solution 5 - JavaÓscar LópezView Answer on Stackoverflow
Solution 6 - JavaआनंदView Answer on Stackoverflow
Solution 7 - JavaBlizzaNView Answer on Stackoverflow
Solution 8 - JavaBob GenomView Answer on Stackoverflow
Solution 9 - JavaAnupam JainView Answer on Stackoverflow
Solution 10 - JavaNadavView Answer on Stackoverflow
Solution 11 - JavaPankajView Answer on Stackoverflow
Solution 12 - JavaFarhan SyedView Answer on Stackoverflow
Solution 13 - JavaAbdul RizwanView Answer on Stackoverflow
Solution 14 - JavaSanAView Answer on Stackoverflow
Solution 15 - JavarmullerView Answer on Stackoverflow
Solution 16 - JavaRaosaheb DeshmukhView Answer on Stackoverflow
Solution 17 - JavakoushickView Answer on Stackoverflow
Solution 18 - Javaceph3usView Answer on Stackoverflow
Solution 19 - Javanatwar kumarView Answer on Stackoverflow
Solution 20 - JavaErkView Answer on Stackoverflow
Solution 21 - Javauser3133925View Answer on Stackoverflow
Solution 22 - JavafabiolimaceView Answer on Stackoverflow
Solution 23 - JavaLekovView Answer on Stackoverflow