java 判斷含有中文的字符串的長度


  • public static boolean isLetter(char c) {   
  •        int k = 0x80;   
  •        return c / k == 0 ? true : false;   
  •    }  
  •   
  • /** 
  •  * 判斷字符串是否為空 
  •  * @param str 
  •  * @return 
  •  */  
  • public static boolean isNull(String str){  
  •     if(str==null||str.trim().equals("")||str.trim().equalsIgnoreCase("null")){  
  •         return true;  
  •     }else{  
  •         return false;  
  •     }  
  • }  
  •   
  • /**  
  •     * 得到一個字符串的長度,顯示的長度,一個漢字或日韓文長度為2,英文字符長度為1  
  •     * @param String s 需要得到長度的字符串  
  •     * @return int 得到的字符串長度  
  •     */   
  •    public static int length(String s) {  
  •        if (s == null)  
  •            return 0;  
  •        char[] c = s.toCharArray();  
  •        int len = 0;  
  •        for (int i = 0; i < c.length; i++) {  
  •            len++;  
  •            if (!isLetter(c[i])) {  
  •                len++;  
  •            }  
  •        }  
  •        return len;  
  •    }  
  •   
  •      
  •    /**  
  •     * 得到一個字符串的長度,顯示的長度,一個漢字或日韓文長度為1,英文字符長度為0.5  
  •     * @param String s 需要得到長度的字符串  
  •     * @return int 得到的字符串長度  
  •     */   
  •    public static double getLength(String s) {  
  •     double valueLength = 0;    
  •        String chinese = "[\u4e00-\u9fa5]";    
  •        // 獲取字段值的長度,如果含中文字符,則每個中文字符長度為2,否則為1    
  •        for (int i = 0; i < s.length(); i++) {    
  •            // 獲取一個字符    
  •            String temp = s.substring(i, i + 1);    
  •            // 判斷是否為中文字符    
  •            if (temp.matches(chinese)) {    
  •                // 中文字符長度為1    
  •                valueLength += 1;    
  •            } else {    
  •                // 其他字符長度為0.5    
  •                valueLength += 0.5;    
  •            }    
  •        }    
  •        //進位取整    
  •        return  Math.ceil(valueLength);    
  •    }
  • 轉載來源:http://blog.csdn.net/z69183787/article/details/18843925

  • 免責聲明!

    本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



     
    粵ICP備18138465號   © 2018-2025 CODEPRJ.COM