按字节截取含有中文汉字的字符串

来源:互联网 发布:mac终端停止命令行 编辑:程序博客网 时间:2024/05/03 09:15
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;}


 

原创粉丝点击