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

來源:互聯網
上載者:User

標籤:substr   start   for   turn   ring   nes   字串   word   char   

  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.    }
  63. 轉載來源:http://blog.csdn.net/z69183787/article/details/18843925

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.