java 判断含有中文的字符串的长度

  1. public static boolean isLetter(char c) {   
  2.        int k = 0x80;   
  3.        return c / k == 0 ? true : false;   
  4.    }  
  5.   
  6. /** 
  7.  * 判断字符串是否为空 
  8.  * @param str 
  9.  * @return 
  10.  */  
  11. public static boolean isNull(String str){  
  12.     if(str==null||str.trim().equals("")||str.trim().equalsIgnoreCase("null")){  
  13.         return true;  
  14.     }else{  
  15.         return false;  
  16.     }  
  17. }  
  18.   
  19. /**  
  20.     * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1  
  21.     * @param String s 需要得到长度的字符串  
  22.     * @return int 得到的字符串长度  
  23.     */   
  24.    public static int length(String s) {  
  25.        if (s == null)  
  26.            return 0;  
  27.        char[] c = s.toCharArray();  
  28.        int len = 0;  
  29.        for (int i = 0; i < c.length; i++) {  
  30.            len++;  
  31.            if (!isLetter(c[i])) {  
  32.                len++;  
  33.            }  
  34.        }  
  35.        return len;  
  36.    }  
  37.   
  38.      
  39.    /**  
  40.     * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为1,英文字符长度为0.5  
  41.     * @param String s 需要得到长度的字符串  
  42.     * @return int 得到的字符串长度  
  43.     */   
  44.    public static double getLength(String s) {  
  45.     double valueLength = 0;    
  46.        String chinese = "[\u4e00-\u9fa5]";    
  47.        // 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1    
  48.        for (int i = 0; i < s.length(); i++) {    
  49.            // 获取一个字符    
  50.            String temp = s.substring(i, i + 1);    
  51.            // 判断是否为中文字符    
  52.            if (temp.matches(chinese)) {    
  53.                // 中文字符长度为1    
  54.                valueLength += 1;    
  55.            } else {    
  56.                // 其他字符长度为0.5    
  57.                valueLength += 0.5;    
  58.            }    
  59.        }    
  60.        //进位取整    
  61.        return  Math.ceil(valueLength);    
  62.    }  

猜你喜欢

转载自blog.csdn.net/belalds/article/details/80647114
今日推荐