Reputation: 20473
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
Upvotes: 360
Views: 869432
Reputation: 3728
…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
Upvotes: 0
Reputation: 12417
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("[$]", "");
Upvotes: 3
Reputation: 2058
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 ;) ):
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));
}
}
Upvotes: 3
Reputation: 3728
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.
Upvotes: 0
Reputation: 928
Use replaceAll instead of replace
str = str.replaceAll("X,"");
This should give you the desired answer.
Upvotes: 2
Reputation: 21186
Using
public String replaceAll(String regex, String replacement)
will work.
Usage would be str.replace("X", "");
.
Executing
"Xlakjsdf Xxx".replaceAll("X", "");
returns:
lakjsdf xx
Upvotes: 48
Reputation: 49
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();
}
}
Upvotes: 3
Reputation: 9
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);
}
}
}
Upvotes: -1
Reputation: 184
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)
Upvotes: 2
Reputation: 4233
If you want to do something with Java Strings, Commons Lang StringUtils is a great place to look.
StringUtils.remove("TextX Xto modifyX", 'X');
Upvotes: 29
Reputation: 269368
Try using the overload that takes CharSequence
arguments (eg, String
) rather than char
:
str = str.replace("X", "");
Upvotes: 578
Reputation: 77
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.
Upvotes: 6
Reputation: 1
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.
Upvotes: -4