Remove all occurrences of char from string

JavaStringCharacter

Java Problem Overview


I can use this:

String str = "TextX Xto modifyX";
str = str.replace('X','');//that does not work because there is no such character ''

Is there a way to remove all occurrences of character X from a String in Java?

I tried this and is not what I want: str.replace('X',' '); //replace with space

Java Solutions


Solution 1 - Java

Try using the overload that takes CharSequence arguments (eg, String) rather than char:

str = str.replace("X", "");

Solution 2 - Java

Using

public String replaceAll(String regex, String replacement)

will work.

Usage would be str.replace("X", "");.

Executing

"Xlakjsdf Xxx".replaceAll("X", "");

returns:

lakjsdf xx

Solution 3 - Java

If you want to do something with Java Strings, Commons Lang StringUtils is a great place to look.

StringUtils.remove("TextX Xto modifyX", 'X');

Solution 4 - Java

String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";
	
for(String t : arr)
	ans+=t;

This is the example for where I have removed the character - from the String.

Solution 5 - Java

Hello Try this code below

public class RemoveCharacter {
	
	public static void main(String[] args){
		String str = "MXy nameX iXs farXazX";
		char x = 'X';
		System.out.println(removeChr(str,x));
	}
	
	public static String removeChr(String str, char x){
		StringBuilder strBuilder = new StringBuilder();
		char[] rmString = str.toCharArray();
		for(int i=0; i<rmString.length; i++){
			if(rmString[i] == x){
				
			} else {
				strBuilder.append(rmString[i]);
			}
		}
		return strBuilder.toString();
	}
}

Solution 6 - Java

I like using RegEx in this occasion:

str = str.replace(/X/g, '');

where g means global so it will go through your whole string and replace all X with ''; if you want to replace both X and x, you simply say:

str = str.replace(/X|x/g, '');

(see my fiddle here: fiddle)

Solution 7 - Java

Use replaceAll instead of replace

str = str.replaceAll("X,"");

This should give you the desired answer.

Solution 8 - Java

Evaluation of main answers with a performance benchmark which confirms concerns that the current chosen answer makes costly regex operations under the hood

To date the provided answers come in 3 main styles (ignoring the JavaScript answer ;) ):

  • Use String.replace(charsToDelete, ""); which uses regex under the hood
  • Use Lambda
  • Use simple Java implementation

In terms of code size clearly the String.replace is the most terse. The simple Java implementation is slightly smaller and cleaner (IMHO) than the Lambda (don't get me wrong - I use Lambdas often where they are appropriate)

Execution speed was, in order of fastest to slowest: simple Java implementation, Lambda and then String.replace() (that invokes regex).

By far the fastest implementation was the simple Java implementation tuned so that it preallocates the StringBuilder buffer to the max possible result length and then simply appends chars to the buffer that are not in the "chars to delete" string. This avoids any reallocates that would occur for Strings > 16 chars in length (the default allocation for StringBuilder) and it avoids the "slide left" performance hit of deleting characters from a copy of the string that occurs is the Lambda implementation.

The code below runs a simple benchmark test, running each implementation 1,000,000 times and logs the elapsed time.

The exact results vary with each run but the order of performance never changes:

Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms

The Lambda implementation (as copied from Kaplan's answer) may be slower because it performs a "shift left by one" of all characters to the right of the character being deleted. This would obviously get worse for longer strings with lots of characters requiring deletion. Also there might be some overhead in the Lambda implementation itself.

The String.replace implementation, uses regex and does a regex "compile" at each call. An optimization of this would be to use regex directly and cache the compiled pattern to avoid the cost of compiling it each time.

package com.sample;

import java.util.function.BiFunction;
import java.util.stream.IntStream;

public class Main {

	static public String deleteCharsSimple(String fromString, String charsToDelete)
	{
		StringBuilder buf = new StringBuilder(fromString.length()); // Preallocate to max possible result length
		for(int i = 0; i < fromString.length(); i++)
			if (charsToDelete.indexOf(fromString.charAt(i)) < 0)
				buf.append(fromString.charAt(i));   // char not in chars to delete so add it
		return buf.toString();
	}

	static public String deleteCharsLambda(String fromString1, String charsToDelete)
	{
		BiFunction<String, String, String> deleteChars = (fromString, chars) -> {
			StringBuilder buf = new StringBuilder(fromString);
			IntStream.range(0, buf.length()).forEach(i -> {
				while (i < buf.length() && chars.indexOf(buf.charAt(i)) >= 0)
					buf.deleteCharAt(i);
			});
			return (buf.toString());
		};

		return deleteChars.apply(fromString1, charsToDelete);
	}

	static public String deleteCharsReplace(String fromString, String charsToDelete)
	{
		return fromString.replace(charsToDelete, "");
	}


	public static void main(String[] args)
    {
        String str = "XXXTextX XXto modifyX";
	    String charsToDelete = "X";  // Should only be one char as per OP's requirement

	    long start, end;

	    System.out.println("Start simple");
	    start = System.currentTimeMillis();

	    for (int i = 0; i < 1000000; i++)
		    deleteCharsSimple(str, charsToDelete);

	    end = System.currentTimeMillis();
	    System.out.println("Time: " + (end - start));

	    System.out.println("Start lambda");
	    start = System.currentTimeMillis();
	    for (int i = 0; i < 1000000; i++)
	    	deleteCharsLambda(str, charsToDelete);

	    end = System.currentTimeMillis();
	    System.out.println("Time: " + (end - start));

	    System.out.println("Start replace");
	    start = System.currentTimeMillis();

	    for (int i = 0; i < 1000000; i++)
		    deleteCharsReplace(str, charsToDelete);

	    end = System.currentTimeMillis();
	    System.out.println("Time: " + (end - start));
    }
}

Solution 9 - Java

here is a lambda function which removes all characters passed as string

BiFunction<String,String,String> deleteChars = (fromString, chars) -> {
  StringBuilder buf = new StringBuilder( fromString );
  IntStream.range( 0, buf.length() ).forEach( i -> {
    while( i < buf.length() && chars.indexOf( buf.charAt( i ) ) >= 0 )
      buf.deleteCharAt( i );
  } );
  return( buf.toString() );
};

String str = "TextX XYto modifyZ";
deleteChars.apply( str, "XYZ" ); // –> "Text to modify"

This solution takes into acount that the resulting String – in difference to replace() – never becomes larger than the starting String when removing characters. So it avoids the repeated allocating and copying while appending character-wise to the StringBuilder as replace() does.
Not to mention the pointless generation of Pattern and Matcher instances in replace() that are never needed for removal.
In difference to replace() this solution can delete several characters in one swoop.

Solution 10 - Java

You will need to put the characters needs to be removed inside the square brackets during the time of replacement. The example code will be as following:

String s = "$116.42".replaceAll("[$]", "");

Solution 11 - Java

…another lambda
copying a new string from the original, but leaving out the character that is to delete

String text = "removing a special character from a string";

int delete = 'e';
int[] arr = text.codePoints().filter( c -> c != delete ).toArray();

String rslt = new String( arr, 0, arr.length );

gives: rmoving a spcial charactr from a string

Solution 12 - Java

package com.acn.demo.action;

public class RemoveCharFromString {
	
	static String input = "";
	public static void main(String[] args) {
		input = "abadbbeb34erterb";
		char token = 'b';
		removeChar(token);
	}

	private static void removeChar(char token) {
		// TODO Auto-generated method stub
		System.out.println(input);
		for (int i=0;i<input.length();i++) {
			if (input.charAt(i) == token) {
			input = input.replace(input.charAt(i), ' ');
				System.out.println("MATCH FOUND");
			}
			input = input.replaceAll(" ", "");
			System.out.println(input);
		}
	}
}

Solution 13 - Java

You can use str = str.replace("X", ""); as mentioned before and you will be fine. For your information '' is not an empty (or a valid) character but '\0' is.

So you could use str = str.replace('X', '\0'); instead.

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
QuestionevilReikoView Question on Stackoverflow
Solution 1 - JavaLukeHView Answer on Stackoverflow
Solution 2 - JavaMichael WilesView Answer on Stackoverflow
Solution 3 - JavaArend v. ReinersdorffView Answer on Stackoverflow
Solution 4 - JavaJavaChampView Answer on Stackoverflow
Solution 5 - JavaRajuView Answer on Stackoverflow
Solution 6 - JavaGerrit BView Answer on Stackoverflow
Solution 7 - JavaAyushi JainView Answer on Stackoverflow
Solution 8 - JavaVolksmanView Answer on Stackoverflow
Solution 9 - JavaKaplanView Answer on Stackoverflow
Solution 10 - JavaArefeView Answer on Stackoverflow
Solution 11 - JavaKaplanView Answer on Stackoverflow
Solution 12 - Javaharikrishna tekkamView Answer on Stackoverflow
Solution 13 - JavaFoivosView Answer on Stackoverflow