replace all + with -

2020-05-09 18:58发布

I am trying to replace a + character into a hyphen I have in my string.

String str = "word+word";
str.replaceAll('+ ', '-');

I tried using replace but it throwing an exception.Is there any other method to do this.

标签: java
6条回答
对你真心纯属浪费
2楼-- · 2020-05-09 19:08

Use

str = str.replaceAll("\\+", "-");

A few errors in your code :

  • replaceAll takes strings, not chars
  • the + char must be escaped as the first argument is a regular expression (and \ itself must be escaped in java string literals)
  • you must take the return of the function : as String is immutable the function doesn't change it but returns another string
查看更多
男人必须洒脱
3楼-- · 2020-05-09 19:15

The replaceAll function takes a regular expression as its first argument. It so happens that + is a special character in regular expression language. Try replacing + with \\+. This will escape the plus sign, thus making the code to treat it like a normal character.

Also, the replaceAll method yields a string, so that will not work. Try doing:

String str = "word+word";
str = str.replaceAll("\\+ ", "-");
查看更多
Summer. ? 凉城
4楼-- · 2020-05-09 19:15

Use "" as opposed to '' in replaceAll.

String java.lang.String.replaceAll(String regex, String replacement)

查看更多
家丑人穷心不美
5楼-- · 2020-05-09 19:17

If you are not sure about the escape sequence you need to use,

You could simply do this.

str = str.replaceAll(Pattern.quote("+"), "-");

This will automatically escape the regex predefined tokens to match in a literal way

查看更多
疯言疯语
6楼-- · 2020-05-09 19:21

Just use replace:

str = str.replace('+', '-');

This one doesn't work on regex but take characters as they are.
Also as you see you have to reassing value again to your str variable because String in Java are immutable. In this case method replace doesn't change current String (str) but create new one with replaced + to '-'.

查看更多
爷的心禁止访问
7楼-- · 2020-05-09 19:25

`replaceAll´ is for regular expressions and strings are immutable. Use:

str = str.replace("+", "-");

instead...

查看更多
登录 后发表回答