Replacing characters in Java

2020-04-19 05:16发布

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 t1 = t;
String t2 = t;
t.replace("\u005B", "");
t.replace("\u005D", "");
t1.replace("[", "");
t1.replace("]", "");
t2.replace("\\]", "");
t2.replace("\\[", "");
System.out.println(t+" , "+t1+" , "+t2);

The resulting output is still "[javatag] , [javatag] , [javatag]" without the "[" and "]" being replaced.

What should I do to replace those "[" and "]" characters ?

6条回答
贼婆χ
2楼-- · 2020-04-19 05:31

String.replace doesn't work that way. You have to use something like t = t.replace("t", "")

查看更多
Ridiculous、
3楼-- · 2020-04-19 05:34

Strings in Java are immutable, meaning you can't change them. Instead, do t1 = t1.replace("]", "");. This will assign the result of replace to t1.

查看更多
家丑人穷心不美
4楼-- · 2020-04-19 05:42

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.

查看更多
唯我独甜
5楼-- · 2020-04-19 05:43

Strings are immutable so

t.replace(....);

does nothing

you need to assign the output to some variable like

t = t.replace(....);
查看更多
等我变得足够好
6楼-- · 2020-04-19 05:44
t.replace(....);

gives you a String (return a string)

you can reassign the origin variable name to the new string

and the old string will later been garbage-collected :)

查看更多
等我变得足够好
7楼-- · 2020-04-19 05:51

String.replace() returns a new string after replacing the required characters. Hence you need to do it in this way:

String t = "[javatag]";
t = t.replace("[","");
t = t.replace("]","");
查看更多
登录 后发表回答