Java判断是否包含中文/中文字符
程序员文章站
2022-03-04 15:00:54
...
判断是否有中文或者字符,其实可以用正则表达式判断; 这里直接用代码判断:
//判断是否有中文/中文字符
private static final JSONObject isChinese(String c) {
JSONObject object = null;
int i = 0;
boolean flag = false;
for (char c1 : c.toCharArray()) {
i++;
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c1);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
flag = true;
}
if (!flag && c1 >= 0x4E00 && c1 <= 0x9FA5) {
flag = true;
}
if (flag) {
object = new JSONObject();
object.put("i", i);//第几个有问题
object.put("val", c1);//有问题的值
return object;
}
}
return object;
}
//调用
//判断是否有中文数据
JSONObject chinese = null;
if ((chinese = isChinese(param.getpVal())) != null) {
return AjaxResult.err("第" + chinese.getString("i") + "个为中文/中文字符(" + chinese.getString("val") + "),请检查!");
}