java按照字節長度獲取字符串長度

/**
* @功能描述: 按照字節長度獲取字符串長度
* @param str
* @param n
* @return
* @throws Exception 
* @date 2017年9月4日
* @author WEISANGENG
*/
@SuppressWarnings("static-access")
public static String substring(String str, int n)
throws Exception {
int reInt = 0;
String reStr = "";
if (str == null)
return "";
char[] tempChar = str.toCharArray();
for (int i = 0; (i < tempChar.length && n > reInt); i++) {
String s1 = str.valueOf(tempChar[i]);
byte[] b = s1.getBytes();
reInt += b.length;
reStr += tempChar[i];
}

return reStr;
}

/**
* @功能描述: 根據指定長度截取字符串
* @param s
* @param n
* @return 
* @date 2017年9月4日
* @author WEISANGENG
*/
    public static String subString (String s ,int n){
        if (s == null) {
            return "";
        }
        Pattern p = Pattern.compile("^[\\u4e00-\\u9fa5]|[\\uff08]|[\\uff09]$");
        int i = 0, j = 0;
        char []ch = s.toCharArray();
        char c;
        for (int k=0; k< ch.length; k++) {
            c = ch[k];
            Matcher m = p.matcher(String.valueOf(c));
            i += m.find() ? 2 : 1;
            ++j;
            if(i == n) 
                break;
            if(i > n) {
                --j;
                break;
            }
        }
        return s.substring(0, j);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章