Here you can find the source of substring(String str, int toCount)
public static String substring(String str, int toCount)
//package com.java2s; //License from project: Open Source License public class Main { public static String substring(String str, int toCount) { return substring(str, toCount, ".."); }//from w w w . jav a2 s .c o m public static String substring(String str, int len, String more) { if (str == null || "".equals(str) || len < 1) { return ""; } char[] chars = str.toCharArray(); int count = 0; int charIndex = 0; for (int i = 0; i < chars.length; i++) { int charLength = getCharLen(chars[i]); if (count <= len - charLength) { count += charLength; charIndex++; } else { break; } } if (charIndex == chars.length) { return new String(chars, 0, charIndex); } else { return new String(chars, 0, charIndex) + more; } } private static int getCharLen(char c) { int k = 0x80; return c / k == 0 ? 1 : 2; } }