编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。

package my0414;

import java.io.UnsupportedEncodingException;

public class StringText {

	/**
	 * @param args
	 * @throws UnsupportedEncodingException 
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		
		String str="k%11!*好aa!、小一ki大0家好";
		int m=trimGBK(str.getBytes(),8);
		System.out.println(str.substring(0, m));
		
		System.out.println(mysubString(str,8));
	}
	 public static int  trimGBK(byte[] buf,int n){
		 boolean chinese=false;
		 int num=0;
		 for(int i=0;i<n;i++){
			 System.out.println(buf[i]);
			 if(buf[i]<0&&!chinese){
				 chinese=true;
			 }else{
				 num++;
				 chinese=false;
			 }
		 }
		 return num;
	 }
	 public static String mysubString(String str,int sublen){
		 String subStr=str.substring(0,sublen);
		 int tempSublen=sublen;
		 int subStrlen=subStr.getBytes().length;
		 while(subStrlen>sublen){
			 
			 tempSublen--;
			 subStrlen=str.substring(0,tempSublen).getBytes().length;
		
		 }
		 return str.substring(0,tempSublen);
		 
	 }
}

  

原文地址:https://www.cnblogs.com/qiaomu/p/4425934.html