Here you can find the source of substring(String str, int srcPos, int specialCharsLength)
public static String substring(String str, int srcPos, int specialCharsLength)
//package com.java2s; public class Main { public static String substring(String str, int srcPos, int specialCharsLength) { if (str == null || "".equals(str) || specialCharsLength < 1) { return ""; }//from w w w .ja va 2 s . c o m if (srcPos < 0) { srcPos = 0; } if (specialCharsLength <= 0) { return ""; } char[] chars = str.toCharArray(); if (srcPos > chars.length) { return ""; } int strLength = 0; for (int i = 0; i < chars.length; i++) { strLength += getSpecialCharLength(chars[i]); } if (strLength < specialCharsLength) { return str; } int charsLength = getCharsLength(chars, specialCharsLength); return new StringBuffer() .append(new String(chars, srcPos, charsLength)) .append("...").toString(); } private static int getSpecialCharLength(char c) { if (isLetter(c)) { return 1; } else { return 2; } } private static int getCharsLength(char[] chars, int specialCharsLength) { int count = 0; int normalCharsLength = 0; for (int i = 0; i < chars.length; i++) { int specialCharLength = getSpecialCharLength(chars[i]); if (count <= specialCharsLength - specialCharLength) { count += specialCharLength; normalCharsLength++; } else { break; } } return normalCharsLength; } public static boolean isLetter(char c) { int k = 0x80; return c / k == 0 ? true : false; } }