Stripslashes in Android/Java

2019-09-15 02:20发布

问题:

I've a webservice running and Android devices reading data from it. The data I want to send, is slashed by the server, to avoid hacking issues. Once its escapped, it's being saved into the database.

But when I'm reading this data again, it's being returned like this: "Baba O\'Riley" instead of "Baba O'Riley".

I think its pretty "correct" and that what I've to do, is to clean the string I get of backslashes with a function like Stripslashes in PHP.

http://es1.php.net/manual/es/function.stripslashes.php

However, I couldn't find any function to do this in Java.

Any idea?

回答1:

You can use string.replace() function. See String replace a Backslash and How to replace backward slash to forward slash using java?

String replacedStr = stringname.replace("\\", "");


回答2:

I'm having trouble finding a genuinely suitable Java function for this, but this is at least better than the currently accepted answer:

String replacedStr = stringname.replace("\\\\", "!~!").replace("\\", "").replace("!~!", "\\");

(Replace !~! with some sequence of characters that's sufficiently unlikely to appear in the string)

This method works by replacing double backslashes with a sufficiently uncommon marker for safekeeping, stripping all backslashes, then changing the uncommon marker back to a single backslash. It's slower than the state machine that PHP uses, since it makes three passes, but that's unlikely to make a noticeable difference.



回答3:

\n,\r, \t,\v,\f,\e....

When dealing with characters listed above the JAVA function

 String replacedStr = stringname.replace("\\", "");

are different from PHP function