2014年7月21日 星期一

[JAVA] String 相關工具

   /**
     * 取得字串長度(中文為2,數字為1,半形為1,全形為2)
     *
     * @param value
     * @return
     */
    public static int strLength(final String value) {
        int length = 0;
        String str = (value == null) ? "" : value; // 避免null,造成exception
        char character;
       
        for (int i = 0; i < str.length(); i++) {
            character = str.charAt(i);
            // 若不為英文字,或半形時,長度加1(長度算2)
            if (Character.UnicodeBlock.of(character) != Character.UnicodeBlock.BASIC_LATIN || !isHalfWidth(character)) {
                length++;
            }
           
            length++;
        }
       
        return length;
    }

    /**
     * 判斷是否為半形
     *
     * @param character
     * @return
     */
    public static boolean isHalfWidth(char c)   {
        return '\u0000' <= c && c <= '\u00FF'
            || '\uFF61' <= c && c <= '\uFFDC'
            || '\uFFE8' <= c && c <= '\uFFEE' ;

    }


沒有留言:

張貼留言