0

Hi I'd like to replace a char in a String. My problem is that at first you don't know which char it is, so in some cases I get an error message when my char is for example '+'. I don't want my char being interpreted as regex, so what should I do?

May code should be something like this:

String test = "something";
char ca = input.chatAt(0);
input = input.replaceAll("" + ca, "");

I hope you can help me.

4
  • And if you want to replace a literal string by another literal string, then use String.replace(from, to). Reading the javadoc is all you have to do to find these easy solutions. Commented Apr 22, 2014 at 11:39
  • My code works perfectly with every char which is NOT '+', '*', '?',... but it should also be possible with these chars. Commented Apr 22, 2014 at 11:40
  • Use String.replace() instead of String.replaceAll(). Commented Apr 22, 2014 at 11:41
  • Thank you! I didn't expect it to be that easy. Commented Apr 22, 2014 at 11:43

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.