Here you can find the source of truncate(String text, int size, String charsetName)
public static String truncate(String text, int size, String charsetName)
//package com.java2s; public class Main { public static String truncate(String text, int size) { return truncate(text, size, "UTF-8"); }/*from w ww . ja va 2s. com*/ public static String truncate(String text, int size, String charsetName) { return truncate(text, 0, size, charsetName, 3); } public static String truncate(String text, int start, int size, String charsetName) { return truncate(text, start, size, charsetName, 3); } public static String truncate(String text, int start, int size, String charsetName, int charBytes) { if (text == null) { return ""; } int count = 0; StringBuilder stxt = new StringBuilder(size); char[] chars = text.toCharArray(); for (int i = start; (i < chars.length && size > count); i++) { try { String s = String.valueOf(chars[i]); count += s.getBytes(charsetName).length; } catch (Exception e) { count += charBytes; } if (count <= size) { stxt.append(chars[i]); } } return stxt.toString(); } }