因此,我有一个包含文本和其他数据的char[]数组。
如何从char[]数组中提取中文文本?现在我可以把英语说得好
public String getString(int index, int length) {
String str = "";
for (int i = 0; i < length && this.data[index + i] != 0; i++)
str = str + this.data[index + i];
return str;
}那我就试试这个:
try {
String charset = "GB18030";
String str = new String(m.target.getBytes("UTF-16"), "GB18030");
System.out.println(str);
System.out.println(str.equals("大家"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}m.target是我从上面的byte[]数组中获得的带有getString()的字符串。我尝试过不同的编码和组合,它们都不会正确显示文本( str.equals("大家") ),也不会返回true (“大家”)
编辑
用这种方法可以成功地得到汉字。
public String test(int index, int length) {
byte[] t = new byte[this.data.length];
for (int i = 0; i < this.data.length; i++)
t[i] = (byte) this.data[i];
try {
return new String(t, index, length, "GB18030");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}但我现在的问题是..。我以为一个字节的最大值是127?字节数组如何保存高字节汉字?我能否安全地将缓冲区更改为byte[]而不是char[]?
发布于 2012-01-15 21:06:45
Java中的char和String都是Unicode。只要在Java代码中对其进行操作,您就不必关心这个问题。在转换到/从byte[]数组或从IO流到/从IO流时指定编码。
要声明包含汉字的字符串,可以使用转义序列,或者只需用代码编写它们,但是您必须关心文件编码。UTF-8格式现在是准标准的,它既受IDE的支持(如Eclipse),也受到构建工具(maven、ant)的支持。
所以你只需要写
char ch = '大';
char[] chrs = new char[]{'大','家'};
String str = "大家";要从例如InputStreamReader UTF-16编码文件中读取汉字,您可以使用指定正确的编码,然后可以读取字符串f.e。借助BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream("myfile.txt"), "UTF-16"));https://stackoverflow.com/questions/8873121
复制相似问题