/** * 写一个方法 String left(String str ,int n) <br> * str字符串中可能包含中文,中文是2bytes,实现的功能是<br> * 如:“中abc12” n=4 则该方法返回“中ab”<br> * “中abc国a” n=6 则返回“中abc”<br> * 中文是一半时不返回 * * @author Fee Share */ public class Test { public static void main(String[] args) { String s = "我是acf中d国人adfgdd123"; for (int i = 0; i <= s.getBytes().length; i++) { System.out.printf("%2d=%s\n", i, getSubString(s, i)); } } private static String getSubString(String s, int n) { int count = 0; int offset = 0; char[] c = s.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] > 256) { offset = 2; count += 2; } else { offset = 1; count++; } if (count == n) { return s.substring(0, i + 1); } if ((count == n + 1 && offset == 2)) { return s.substring(0, i); } } return ""; } }
截取指定长度的字符串,不能返回半个汉字
最新推荐文章于 2022-09-30 16:28:48 发布