这听起来可能是一个基本问题。但我被困在这里。我想用一个等价的Unicode值(" with \u0022
)替换字符串的所有双引号。
在C#中是可能的。但是不知道如何用Java做到这一点。
C# - C# Working snippet
Java - Java Non working snippet
注意:在Java中,我可以使用\\u0022
。但在这种情况下,它会转义\
而不是双引号。
答案 0 :(得分:3)
As explained in the other question:
The problem is that the Unicode replacement is done very early in compilation. Unicode escapes aren't just valid in strings and character literals (as other escape sequences such as \t are) - they're valid anywhere in code. -- Jon Skeet
So "\u0022"
is actually equivalent to """
, which is syntactically wrong in Java.
This will work:
System.out.println(xyz.replaceAll("\"", ""+'\u0022'));
And if you are only replacing chars:
System.out.println(xyz.replace('\"', '\u0022'));
But, \u0022
is just another form of the "
character. If you are after a general solution, most of the characters won't give you this problem in the first place, because they are not messing with the string literals like "
does.
答案 1 :(得分:2)
We can't represent the same string with a single Unicode escape. """ same as "\u0022" in java, you can do it in this way
public static void main(String args[])
{
System.out.println("Hello, World!");
String xyz = "Hello \"World";
System.out.println(xyz.replaceAll("\"", "\u005c\u0022"));
}
答案 2 :(得分:1)
这里你去:
public static void main(String args[]){
String yourJsonString = "Test\"TEST";
yourJsonString = yourJsonString.replaceAll("\"", "\\\\u0022");
System.err.println(yourJsonString);
}
将打印Test\u0022TEST
答案 3 :(得分:1)
试试这个:
import java.util.*; import java.lang.*;
class Rextester {
public static void main(String args[])
{
System.out.println("Hello, World!");
String xyz = "Hello \"World";
System.out.println(xyz.replaceAll("\"", Character.toString((char)0x0022)));
} }
答案 4 :(得分:1)
You can also do it like this -
String s = "Hello \"world";
System.out.println(s.replace('\"', (char) (0x22)));
It is important to represent the char's value as hex value, by adding 0x
in front of it.
答案 5 :(得分:1)
No in a java source text "
and \u0022
are not only the same, they are identical, as with reading \u0022
is replaced with the corresponding char "
.
You could write:
public \u0063lass C {
If you want to write JSON text with the same u-escaping:
s = s.replace("\"", "\\u0022");
However it might very well be that also some JSON reader might recognize that as "
. So, maybe:
s = s.replace("\"", "\\\"");
might be more successful.
答案 6 :(得分:0)
One way you can do this:
public class MainTester {
public static void main(String args[])
{
System.out.println("Hello, World!");
String xyz = "Hello \"World";
System.out.println(xyz.replaceAll("\"", "\u005c\u0022"));
}
}
Output:
Hello "World