Replacing characters in Java

前端 未结 6 1225
囚心锁ツ
囚心锁ツ 2021-01-25 16:05

I tried to replace characters in String which works sometimes and does not work most of the time.

I tried the following:

String t = \"[javatag]\";
String         


        
6条回答
  •  情话喂你
    2021-01-25 16:52

    String objects in java are immutable. You can't change them.

    You need:

    t2 = t2.replace("\\]", "");
    

    replace() returns a new String object.

    Edit: Because ... I'm breaking away from the pack

    And since this is the case, the argument is actually a regex, and you want to get rid of both brackets, you can use replaceAll() instead of two operations:

    t2 = t2.replaceAll("[\\[\\]]", "");
    

    This would get rid of both opening and closing brackets in one fell swoop.

提交回复
热议问题