Java, Removing backslash in string object

2020-02-06 10:47发布

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.

4条回答
劳资没心,怎么记你
2楼-- · 2020-02-06 10:56

See String.replace(CharSequence, CharSequence)

String myUrl = "http:\\/\\/www.example.com\\/example";
myUrl = myUrl.replace("\\","");
查看更多
聊天终结者
3楼-- · 2020-02-06 11:00

Try this:

return myUrl.replaceAll("\\\\(.)", "\\/");
查看更多
Juvenile、少年°
4楼-- · 2020-02-06 11:13

@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 ...)

查看更多
Animai°情兽
5楼-- · 2020-02-06 11:22

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());
查看更多
登录 后发表回答