天天看點

Java 判斷是否為漢字 判斷是否為亂碼 判斷字元串是否為雙整型數字 整數 數字

/**

  * 判斷是否為漢字

  * 

  * @param str

  * @return

  */

 public static boolean isGBK(String str) {

  char[] chars = str.toCharArray();

  boolean isGBK = false;

  for (int i = 0; i < chars.length; i++) {

   byte[] bytes = ("" + chars[i]).getBytes();

   if (bytes.length == 2) {

    int[] ints = new int[2];

    ints[0] = bytes[0] & 0xff;

    ints[1] = bytes[1] & 0xff;

    if (ints[0] >= 0x81 && ints[0] <= 0xFE && ints[1] >= 0x40

      && ints[1] <= 0xFE) {

     isGBK = true;

     break;

    }

   }

  }

  return isGBK;

 }

  * 判斷是否為亂碼

 public static boolean isMessyCode(String str) {

  for (int i = 0; i < str.length(); i++) {

   char c = str.charAt(i);

   // 當從Unicode編碼向某個字元集轉換時,如果在該字元集中沒有對應的編碼,則得到0x3f(即問号字元?)

   //從其他字元集向Unicode編碼轉換時,如果這個二進制數在該字元集中沒有辨別任何的字元,則得到的結果是0xfffd

   //System.out.println("--- " + (int) c);

   if ((int) c == 0xfffd) {

    // 存在亂碼

    //System.out.println("存在亂碼 " + (int) c);

    return true;

  return false; 

 /**

  * 判斷字元串是否為雙整型數字

 public static boolean isDouble(String str) {

  if (StringUtil.isNullOrEmpty(str)) {

   return false;

  Pattern p = Pattern.compile("-*\\d*.\\d*");

  // Pattern p = Pattern.compile("-*"+"​​\\d*"+"."+"\\d​​*");

  return p.matcher(str).matches();

  * 判斷字元串是否為整字

 public static boolean isNumber(String str) {

  Pattern p = Pattern.compile("-*\\d*");

  * 判斷是否為數字

 public static boolean isNumeric(String str)   

 {   

         Pattern pattern = Pattern.compile("[0-9]*");   

         Matcher isNum = pattern.matcher(str);   

        if( !isNum.matches() ) {   

           return false;   

         }   

        return true;   

需要導入 java.util.regex.Pattern 和 java.util.regex.Matcher