Remove all occurrences of char from string
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
Solution 1:
Try using the overload that takes CharSequence
arguments (eg, String
) rather than char
:
str = str.replace("X", "");
Solution 2:
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:
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:
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:
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();
}
}