Java tutorial
//package com.java2s; import java.io.UnsupportedEncodingException; public class Main { public static String truncate(String str, int byteLength) { if (str == null) { return null; } if (str.length() == 0) { return str; } if (byteLength < 0) { throw new IllegalArgumentException("Parameter byteLength must be great than 0"); } int i = 0; int len = 0; int leng = 0; char[] chs = str.toCharArray(); try { leng = str.getBytes("gbk").length; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (leng <= byteLength) return str; while ((len < byteLength) && (i < leng)) { len = (chs[i++] > 0xff) ? (len + 2) : (len + 1); } if (len > byteLength) { i--; } return new String(chs, 0, i) + "..."; } }