replace a char in String

被刻印的时光 ゝ 提交于 2019-12-02 10:15:44

Just don't use regex then.

input = input.replace(String.valueOf(ca), "");

The replaceAll method of String takes the String representation of a regular expression as an argument.

The replace method does not.

See API.

Actually replace method is potentially ambiguous, in case when you replace, lets say "zz" -> "xy" in the "zzz" string (result would be "xyz" and not "zxy").

In its turn, replaceAll is more flexible and it's behaviour is strictly determined. Needless to say, that it is more expensive, than replace.

Definitely, in your case replace is the best choice.

You can Use replace(Char oldChar, Char newChar) function in String class or use the function below:

String replaceChar(String input, char oldChar, char newChar){
    StringBuffer sb = new StringBuffer();    
    for(int i = 0; i<input.length(); i++){
        char c = input.charAt(i);
        if(c == oldChar)
             sb.append(newChar);
        else
             sb.append(c);
    }
    return sb.toString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!