Remove all occurrences of char from string

2019-01-01 10:39发布

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

9条回答
后来的你喜欢了谁
2楼-- · 2019-01-01 11:14

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

str = str.replace("X", "");
查看更多
不再属于我。
3楼-- · 2019-01-01 11:18
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.

查看更多
只若初见
4楼-- · 2019-01-01 11:18

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();
    }
}
查看更多
登录 后发表回答