按字節截取含有中文漢字的字符串
public static void main(String[] args) throws UnsupportedEncodingException { // TODO Auto-generated method stub // 原始字符串 String s = "我ZWR愛JAVA"; System.out.println("原始字符串:" + s); try { System.out.println("截取前1位:" + CutString.substring(s, 1)); System.out.println("截取前2位:" + CutString.substring(s, 2)); System.out.println("截取前4位:" + CutString.substring(s, 4)); System.out.println("截取前6位:" + CutString.substring(s, 6)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
public static String substring(String orignal, int count) throws UnsupportedEncodingException{ if(!"".equals(orignal) && orignal != null){ // 將原始字符串轉換為GBK編碼格式 orignal = new String(orignal.getBytes(), "GBK"); if(count > 0 && count < orignal.length()){ StringBuffer sb = new StringBuffer(); char c; for (int i = 0; i < count; i++) { c = orignal.charAt(i); sb.append(c); if(isChineseChar(c)){ // 遇到中文漢字,截取字節總數減1 --count; } } return sb.toString(); } } return orignal; }
//判斷是否是一個中文漢字 public static boolean isChineseChar(char c) throws UnsupportedEncodingException{ return String.valueOf(c).getBytes("GBK").length > 1; }
最後更新:2017-04-02 06:52:08