Java 中的字符替换
我尝试替换字符串中的字符,该字符有时有效,但大多数时候不起作用。
我尝试了以下操作:
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);
结果输出仍然是“[javatag],[javatag],[javatag]
”,而没有替换“[”和“]”。
我应该怎么做才能替换那些“[”和“]”字符?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
java中的
String
对象是不可变的。你无法改变它们。您需要:
replace()
返回一个新的String
对象。编辑:因为......我要脱离包
既然是这种情况,参数实际上是一个正则表达式,并且你想去掉两个括号,你可以使用
replaceAll()
而不是两个操作:这将一次性消除左括号和右括号。
String
objects in java are immutable. You can't change them.You need:
replace()
returns a newString
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:This would get rid of both opening and closing brackets in one fell swoop.
字符串是不可变的,因此
您不需要
将输出分配给某个变量,例如
Strings are immutable so
does nothing
you need to assign the output to some variable like
Java 中的
String
是不可变的,这意味着您无法更改它们。相反,请执行t1 = t1.replace("]", "");
。这会将replace
的结果分配给 t1。String
s in Java are immutable, meaning you can't change them. Instead, dot1 = t1.replace("]", "");
. This will assign the result ofreplace
to t1.String.replace 不是这样工作的。您必须使用类似
t = t.replace("t", "")
String.replace doesn't work that way. You have to use something like
t = t.replace("t", "")
String.replace() 替换所需字符后返回一个新字符串。因此你需要这样做:
String.replace() returns a new string after replacing the required characters. Hence you need to do it in this way:
给你一个字符串(返回一个字符串),
你可以将原始变量名称重新分配给新字符串
,旧字符串稍后将被垃圾收集
:)
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
:)