import java.io.IOException; public class AnswerB03 { public static void main(String[] args) throws IOException { String s = "我ABC汉DEF"; System.out.println(substring(s, 6)); } public static String substring(String s, int length) { char[] cs = s.toCharArray(); StringBuilder builder = new StringBuilder(); int count = 0; for (char c : cs) { if (isAsc(c)) { count++; } else { count += 2; } if (count > length) { break; } builder.append(c); } return builder.toString(); } public static boolean isAsc(char c) { return c < 128; } }