public static void main(String[] args) throws UnsupportedEncodingException { // TODO Auto-generated method stub // 原始字符串 String s = "我ZWR爱JAVA"; System.out.println("原始字符串:" + s); try { System.out.println("截取前1位:" + CutString.substring(s, 1)); System.out.println("截取前2位:" + CutString.substring(s, 2)); System.out.println("截取前4位:" + CutString.substring(s, 4)); System.out.println("截取前6位:" + CutString.substring(s, 6)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
public static String substring(String orignal, int count) throws UnsupportedEncodingException{ if(!"".equals(orignal) && orignal != null){ // 将原始字符串转换为GBK编码格式 orignal = new String(orignal.getBytes(), "GBK"); if(count > 0 && count < orignal.length()){ StringBuffer sb = new StringBuffer(); char c; for (int i = 0; i < count; i++) { c = orignal.charAt(i); sb.append(c); if(isChineseChar(c)){ // 遇到中文汉字,截取字节总数减1 --count; } } return sb.toString(); } } return orignal; }
//判断是否是一个中文汉字 public static boolean isChineseChar(char c) throws UnsupportedEncodingException{ return String.valueOf(c).getBytes("GBK").length > 1; }