java 字串擷取指定長度位元組數
阿新 • • 發佈:2018-12-24
轉自:https://www.cnblogs.com/jiyanle/p/5161533.html
/** * 返回擷取指定長度位元組數後的字串,多餘部分用“...”代替 * * @作者 jiyanle * @日期 2014-7-6 * @param strs * @param length * @return */ public static String cutStr(String strs, int length) { int sum = 0; String finalStr = ""; if (null == strs || strs.getBytes().length <= length) { finalStr = (strs==null?"":strs); } else { for (int i = 0; i < strs.length(); i++) { String str = strs.substring(i, i + 1); // 累加單個字元位元組數 sum += str.getBytes().length; if (sum > length) { finalStr = strs.substring(0, i) + "..."; break; } } } return finalStr; }