public static boolean hasChinese(String value) {
byte[] valueBytes = value.getBytes();
return value.length() != valueBytes.length;
}这样就可以了,用不着那么费劲
byte[] valueBytes = value.getBytes();
return value.length() != valueBytes.length;
}这样就可以了,用不着那么费劲
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.
Returns:
The resultant byte array至于为啥<0,那与汉字编码有关
而构成英文字母的字节总是正值。至于为什么这么定义,我想你还是看一下unicode码的规范吧。
getBytes()是把一个字符串转成一个byte数组,因为计算机的数据都是基于字符的,也就是说一个字符串实际上就是一个字符流,因此可以转为字符数组。汉字是双字节编码,英文是单字节编码。构成汉字的第一个字节是一个负值,第二个是正值。
而构成英文字母的字节总是正值。至于为什么这么定义,我想你还是看一下unicode码的规范吧。
楼上的几位都说的很详细了!
其实楼主只要知道原理就行了,不要考虑编码到底是怎么实现的!
因为每种编码都有一个算法!
{
public static void main (String [] args)
{
chinese ch=new chinese();
boolean st=ch.hasChinese("谢谢");
System.out.println(st);
}
public static boolean hasChinese(String value) {
boolean blFind; blFind = false;
byte[] valueBytes = value.getBytes();
for (int j = 0; j < value.length(); j++) {
if (valueBytes[j] < 0)
{
blFind = true;
break;
}
}
return blFind;
}
}你的程序没有错,这个程序我输入的是“谢谢”,结果返回的true;
{
public static void main (String [] args)
{
chinese ch=new chinese();
boolean st=ch.hasChinese("лл");
System.out.println(st);
}
public static boolean hasChinese(String value1)
{
byte[] valueBytes = value1.getBytes();
return value1.length() != valueBytes.length;
}
}
这个程序也能实现,而且简单!