java - 包含汉字的字符串转ASCII

标签 java eclipse encoding ascii

这是我的代码,两种方式都给出相同的输出。

String description = "test string with 音樂";
byte[] b = description.getBytes("US-ASCII");

//first way
char[] result = new char[b.length];       
for ( int i = 0; i < b.length; i++ ) {
    result[i] = (char)b[i];
}
System.out.println(new String(result)); //output - test string with ??

//second way
System.out.println(new String(b, "UTF-8")); //output - test string with ??

我正在使用 Eclipse 并在 Run Configuration 下将控制台输出编码更改为 US-ASCII

是否可以获取为US-ASCII编码字符串?

谢谢你!!!

最佳答案

无法将其转换为 US-ASCII 但是,

如果你只是想要 Unicode 转义字符串,那么你可以使用 apache common lang utility,

import org.apache.commons.lang.StringEscapeUtils;

...
StringEscapeUtils.unescapeJava("test string with \u97F3\u6A02"); 
 //gives result : test string with 音樂
StringEscapeUtils.escapeJava("test string with 音樂"); 
 //gives result : test string with \u97F3\u6A02

关于java - 包含汉字的字符串转ASCII,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25160060/

相关文章:

java - 在 Java 中创建静态嵌套类的实例

eclipse - jar 在运行时不可用,为什么不呢?

perl - MediaWiki API 部分名称编码

java - Websphere 上的外部 javascript 字符编码

java - 带有 java.io 的非阻塞服务器

java - Hadoop 映射 : attach sources howto

java - 在java中绘制形状对象(可拖动、可调整大小且可旋转)

eclipse - 这张图片用的是什么UI? (基于节点的用户界面)

java - 使Gradle使用Eclipse项目

html - 为什么 "&#8203;"被注入(inject)到我的 HTML 中?