replace all + with -

后端 未结 6 1463
滥情空心
滥情空心 2021-01-29 06:24

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

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


        
相关标签:
6条回答
  • 2021-01-29 07:05

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

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

    instead...

    0 讨论(0)
  • 2021-01-29 07:09

    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("\\+ ", "-");
    
    0 讨论(0)
  • 2021-01-29 07:16

    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

    0 讨论(0)
  • 2021-01-29 07:21

    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
    0 讨论(0)
  • 2021-01-29 07: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 '-'.

    0 讨论(0)
  • 2021-01-29 07:22

    Use "" as opposed to '' in replaceAll.

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

    0 讨论(0)
提交回复
热议问题