java 判斷字串輸入是中文還是英文
1、根據位元組和字元的長度是否相等判斷字串是純中文還是純英文
- publicclass test {
- publicstaticvoid main(String[] args) {
- String test = "aa";
- byte []bytes = test.getBytes();
- int i = bytes.length;//i為位元組長度
- int j = test.length();//j為字元長度
- System.out.println(i+" "+j);
- }
- }
2、用正則表示式來檢驗
1、判斷輸入型別的最好辦法是正則表示式校驗
2、確定中文文字的unicode範圍[\u4E00-\u9FA5]
3、編寫正則表示式[\u4E00-\u9FA5]+,利用String.matches()方法判斷輸入值是否符合
3、判斷字元是否為中文 未驗證
public class ChineseDistinguisher {
// GENERAL_PUNCTUATION 判斷中文的"號
// CJK_SYMBOLS_AND_PUNCTUATION 判斷中文的。號
// HALFWIDTH_AND_FULLWIDTH_FORMS 判斷中文的,號
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
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) {
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(isChinese('好'));
System.out.println(isChinese('A'));
}
}