Replace Space to Hyphen

前端 未结 7 1117

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

String replaceText = \"AT AT\";
replaceText.replace(\' \', \'-\');

相关标签:
7条回答
  • 2021-02-19 00:04

    Strings are immutable.

    You need to save the value returned by replace(). If you want to replace more than one occurrence, use replaceAll().

    String replaceText = "AT AT";
    replaceText = replaceText.replaceAll(" ", "-");
    

    As @Mark Peters points out in the comments, replace(Char, Char) is sufficient (and faster) for replacing all occurrences.

    String replaceText = "AT AT";
    replaceText = replaceText.replace(' ', '-');
    

    In case this fact bothers you: immutability is a Good Thing.

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