Replace Space to Hyphen

前端 未结 7 1151

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.

提交回复
热议问题