当我从网页读取一些文本时,TextView 中显示的 unicode 字符出现一些问题。
我使用以下代码检索网页内容:
try {
HttpGet request = new HttpGet();
request.addHeader("User-Agent", USER_AGENT);
request.setURI(new URI(wwwlink));
try {
response4 = httpClient.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (URISyntaxException e) {e.printStackTrace();}
try {
in2 = null;
String UTF8 = "UTF-8";
in2 = new BufferedReader (new InputStreamReader(response4.getEntity().getContent(),UTF8));
} catch (IllegalStateException e) {Log.i(tag,e.toString());
} catch (IOException e) {Log.i(tag,e.toString());}
我正在阅读的页面有这个 HTML 标题标签:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
现在的问题是:我读取的行和一些我需要的文本包含这样的 unicode 字符:
20 \u00b0C (20 degree symbol C )
我正在尝试转换它并在 TextView 中显示为度数符号。
以下内容正在运行
textview.settext("\u00b0");
但是当我这样做时,该行包含 unicode 字符:
line = in2.readln;
textview.settext(line);
TextView 将显示以下内容:一些文本\u00b0 一些文本
我已经用模拟器和手机检查了所有内容。
最佳答案
由于您的输入文本包含 unicode 的 java 表示形式,因此您需要手动替换这些字符来纠正它们。这里我举了一个例子,如何替换字符串中的一个字符,只是为了给出一个粗略的想法:
String input = "some text \\u00b0 some text";
Scanner scanner = new Scanner(input);
String unicodeCharStr = scanner.findWithinHorizon("\\\\{1}u[0-9a-fA-F]{4}", 0);
char unicodeChar = (char)(int)Integer.valueOf(unicodeCharStr.substring(2, 6), 16);
input = input.replace(unicodeCharStr, unicodeChar+"");
关于java - android unicode 到可读字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12640106/