您的位置:首页 > 其它

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

2015-04-14 20:15 585 查看
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);

}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐