I have a string that is this
我有一个字符串就是这个
Temperature: 98.6°F (37.0°C)
温度:98.6°F(37.0°C)
Ultimately would like to convert it to look like this
最终想把它转换成这样的样子
98.6\u00b0F (37.0\u00b0C)
I wind up with all the solutions making this a ? or some other char, what i want to do is put a string for the unicode solution there.
我最终得到了所有的解决方案吗?或者其他一些char,我想要做的是为那里的unicode解决方案添加一个字符串。
All of the solutions that i have come across or tried don't seem to work.
我遇到或尝试的所有解决方案似乎都不起作用。
Thanks in advance.
提前致谢。
1 个解决方案
#1
2
Just loop through the characters of the string and replace non-ASCII characters with the Unicode escape:
只需循环遍历字符串的字符,并使用Unicode转义替换非ASCII字符:
String s = "Temperature: 98.6°F (37.0°C)";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0x20 && c <= 0x7E) // visible ASCII character
buf.append(c);
else
buf.append(String.format("\\u%04x", (int) c));
}
String t = buf.toString();
System.out.println(t);
Output
Temperature: 98.6\u00b0F (37.0\u00b0C)
In Java 9+, it's even simpler:
在Java 9+中,它甚至更简单:
String s = "Temperature: 98.6°F (37.0°C)";
String t = Pattern.compile("[^ -~]").matcher(s)
.replaceAll(r -> String.format("\\\\u%04x", (int) r.group().charAt(0)));
System.out.println(t);
#1
2
Just loop through the characters of the string and replace non-ASCII characters with the Unicode escape:
只需循环遍历字符串的字符,并使用Unicode转义替换非ASCII字符:
String s = "Temperature: 98.6°F (37.0°C)";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0x20 && c <= 0x7E) // visible ASCII character
buf.append(c);
else
buf.append(String.format("\\u%04x", (int) c));
}
String t = buf.toString();
System.out.println(t);
Output
Temperature: 98.6\u00b0F (37.0\u00b0C)
In Java 9+, it's even simpler:
在Java 9+中,它甚至更简单:
String s = "Temperature: 98.6°F (37.0°C)";
String t = Pattern.compile("[^ -~]").matcher(s)
.replaceAll(r -> String.format("\\\\u%04x", (int) r.group().charAt(0)));
System.out.println(t);