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 10:54
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);
        }
    }
}
查看更多
几人难应
3楼-- · 2019-01-01 11:06

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

StringUtils.remove("TextX Xto modifyX", 'X');
查看更多
残风、尘缘若梦
4楼-- · 2019-01-01 11:07

Using

public String replaceAll(String regex, String replacement)

will work.

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

Executing

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

returns:

lakjsdf xx
查看更多
孤独总比滥情好
5楼-- · 2019-01-01 11:07

Use replaceAll instead of replace

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

This should give you the desired answer.

查看更多
残风、尘缘若梦
6楼-- · 2019-01-01 11:10

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)

查看更多
与风俱净
7楼-- · 2019-01-01 11:11

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.

查看更多
登录 后发表回答