将“\”替换为String

时间:2012-05-30 07:00:00

标签: java android

我有一个网址字符串

http:\/\/a0.twimg.com\/profile_images\/2170585961\/ETimes_normal.png

我希望"\"替换"",但我使用:

String.replaceAll("\","");

它显示错误。我该怎么办?


(从this url密钥profile_image_url恢复)

2 个答案:

答案 0 :(得分:4)

使用String.replace(CharSequence, CharSequence)代替它,它会重现所有事件!

str = str.replace("\\", "");

从你的例子:

String u = "http:\\/\\/a0.twimg.com\\/profile_images\\/2170585961\\/ETimes_normal.png";
System.out.println(u.replace("\\",""));

输出:

http://a0.twimg.com/profile_images/2170585961/ETimes_normal.png

请注意,String.replaceAll方法采用正则表达式,在这种情况下您不需要它..

答案 1 :(得分:3)

用另一个反斜杠逃避反斜杠:

String.replaceAll("\\\\","");

由于第一个参数是正则表达式,因此应该有两个反斜杠(\是正则表达式中的特殊字符)。但它也是一个字符串,所以每个反斜杠都应该被转义。所以有四个\ s。