字符串替换反斜杠 [英] String replace a Backslash
本文介绍了字符串替换反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用字符串替换反斜杠。
How can I do a string replace of a back slash.
输入源字符串:
sSource = "http://www.example.com\/value";
在上面的字符串中我想用/替换\ /;
In the above String I want to replace "\/" with a "/";
替换后的预期输出:
sSource = "http://www.example.com/value";
我从第三方获取源字符串,因此我可以控制字符串的格式。
I get the Source String from a third party, therefore I have control over the format of the String.
这就是我的尝试
试用1:
sSource.replaceAll("\\", "/");
异常
索引1附近出现意外内部错误
\
Exception Unexpected internal error near index 1 \
试用2:
sSource.replaceAll("\\/", "/");
没有异常,但没有进行必要的替换。什么都不做。
No Exception, but does not do the required replace. Does not do anything.
试用3:
sVideoURL.replace("\\", "/");
没有异常,但没有进行必要的替换。什么都不做。
No Exception, but does not do the required replace. Does not do anything.
推荐答案
sSource = sSource.replace("\\/", "/");
-
String
是不可变的 - 你在其上调用的每个方法都不会改变它的状态。它返回一个保存新状态的新实例。所以你必须将新值赋给变量(它可以是相同的变量) -
replaceAll(..)
使用正则表达式。你不需要那样。 String
is immutable - each method you invoke on it does not change its state. It returns a new instance holding the new state instead. So you have to assign the new value to a variable (it can be the same variable)replaceAll(..)
uses regex. You don't need that.
这篇关于字符串替换反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文