问题
I have a URL like this: http:\/\/www.example.com\/example
in a string object.
Can somebody tell me, how to remove the backslashes?
I am programming for an blackberry system.
回答1:
See String.replace(CharSequence, CharSequence)
String myUrl = "http:\\/\\/www.example.com\\/example";
myUrl = myUrl.replace("\\","");
回答2:
@Kevin's answer contains a fatal problem. The String.replace(char, char)
replaces occurrences of one character with another character. It does not remove characters.
Also ''
is not valid Java because there is no such thing as an empty character.
Here are some solutions that should actually work (and compile!):
String myUrl = "http:\\/\\/www.example.com\\/example";
fixedUrl = myUrl.replace("\\", "");
This simply removes every backslash without considering the context.
fixedUrl = myUrl.replace("\\/", "/");
This replaces escaped forward slashes with plain forward slashes.
fixedUrl = myUrl.replaceAll("\\\\(.)", "\\1");
This "de-escapes" any escape sequences in the String, correctly handling escaped backslashes, and not removing a trailing backslash. This version uses a group to capture the character after the backslash, and then refers to it in the replacement string.
Note that in the final case we are using the replaceAll
method that does regex match / replace, rather than literal String match / replace. Therefore, we need to escape the backslash in the first argument twice; once because a backslash must be escaped in a String literal, and once because a backslash must be escaped in a regex if you want it to stand for a literal backslash character.
I am programming for an blackberry system, in case that is of any relevance.
It is. Blackberry is a J2ME platform, and the J2ME version of String
(see javadoc) only supports String.replace(char, char)
, which (as we noted above) cannot remove characters. On a J2ME platform you need to load the String
into a StringBuffer
, and use a loop and StringBuffer.delete(...)
or StringBuffer.replace(...)
.
(It is stuff like this that makes Android easier to use ...)
回答3:
Try this:
return myUrl.replaceAll("\\\\(.)", "\\/");
回答4:
Only this works for me -
String url = "http:\/\/imgd2.aeplcdn.com\/310x174\/cw\/cars\/ford\/ford-figo-aspire.jpg";
for(int i = 0; i < url.length(); i++)
if(url.charAt(i) == '\\')
url = url.substring(0, i) + url.substring(i + 1, url.length());
来源:https://stackoverflow.com/questions/5104192/java-removing-backslash-in-string-object