package zkktest;
import java.io.UnsupportedEncodingException;
public class test
{
public static void main(String[] args) {
String inStr = "新2鮮";
System.out.println("old Str:" + inStr + "," + inStr.getBytes().length);
System.out.println("0 Str:" + substringByCount(inStr, 0));
System.out.println("1 Str:" + substringByCount(inStr, 1));
System.out.println("2 Str:" + substringByCount(inStr, 2));
System.out.println("3 Str:" + substringByCount(inStr, 3));
System.out.println("4 Str:" + substringByCount(inStr, 4));
System.out.println("5 Str:" + substringByCount(inStr, 5));
System.out.println("6 Str:" + substringByCount(inStr, 6));
System.out.println("7 Str:" + substringByCount(inStr, 7));
System.out.println("8 Str:" + substringByCount(inStr, 8));
String inStr1 = "2新鮮";
System.out.println("old Str:" + inStr1 + "," + inStr1.getBytes().length);
System.out.println("0 Str:" + substringByCount(inStr1, 0));
System.out.println("1 Str:" + substringByCount(inStr1, 1));
System.out.println("2 Str:" + substringByCount(inStr1, 2));
System.out.println("3 Str:" + substringByCount(inStr1, 3));
System.out.println("4 Str:" + substringByCount(inStr1, 4));
System.out.println("5 Str:" + substringByCount(inStr1, 5));
System.out.println("6 Str:" + substringByCount(inStr1, 6));
System.out.println("7 Str:" + substringByCount(inStr1, 7));
System.out.println("8 Str:" + substringByCount(inStr1, 8));
String inStr2 = "新鮮2";
System.out.println("old Str:" + inStr2 + "," + inStr2.getBytes().length);
System.out.println("0 Str:" + substringByCount(inStr2, 0));
System.out.println("1 Str:" + substringByCount(inStr2, 1));
System.out.println("2 Str:" + substringByCount(inStr2, 2));
System.out.println("3 Str:" + substringByCount(inStr2, 3));
System.out.println("4 Str:" + substringByCount(inStr2, 4));
System.out.println("5 Str:" + substringByCount(inStr2, 5));
System.out.println("6 Str:" + substringByCount(inStr2, 6));
System.out.println("7 Str:" + substringByCount(inStr2, 7));
System.out.println("8 Str:" + substringByCount(inStr2, 8));
}
private static String substringByCount(String str, int count) {
StringBuffer buff = new StringBuffer();
if (StringUtils.isNotEmpty(str)) {
if (count > 0) {
char c;
int sumCount = 0;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
sumCount += String.valueOf(c).getBytes(Charset.forName('UTF-8')).length;
if (sumCount > count) {
break;
}
buff.append(c);
}
}
}
return buff.toString();
}
}