Java用的是Unicode 编码char 型变量。
unicode编码范围:
汉字:[0x4e00,0x9fa5](或十进制[19968,40869])
数字:[0x30,0x39](或十进制[48, 57])
小写字母:[0x61,0x7a](或十进制[97, 122])
大写字母:[0x41,0x5a](或十进制[65, 90])
双字节字符编码范围
1.GBK (GB2312/GB18030)
/x00-/xff GBK双字节编码范围
/x20-/x7f ASCII
/xa1-/xff 中文 gb2312
/x80-/xff 中文 gbk
2.UTF-8 (Unicode)
/u4e00-/u9fa5 (中文)
/x3130-/x318F (韩文
/xAC00-/xD7A3 (韩文)
/u0800-/u4e00 (日文)
知道了汉字在Unicode编码中的位置后,我们就可以编写代码来判断了。
第一种方式,用正则表达式去匹配
Java
public boolean checkcountname(String countname){
Pattern p = Pattern.compile(“[\u4e00-\u9fa5]”);
Matcher m = p.matcher(countname);
if (m.find()) {
return true;
}
return false;
}
1
2
3
4
5
6
7
8
publicbooleancheckcountname(Stringcountname){
Patternp=Pattern.compile(“[\u4e00-\u9fa5]”);
Matcherm=p.matcher(countname);
if(m.find()){
returntrue;
}
returnfalse;
}
第二种 判断整个字符串都由汉字组成
public boolean checkname(String name){
int n = 0;
for(int i = 0; i < name.length(); i++) {
n = (int)name.charAt(i);
if(!(19968 <= n && n <40869)) {
return false;
}
}
return true;
}
1
2
3
4
5
6
7
8
9
10
publicbooleancheckname(Stringname){
intn=0;
for(inti=0;i
n=(int)name.charAt(i);
if(!(19968<=n&&n<40869)){
returnfalse;
}
}
returntrue;
}