欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 按字节长度截取字符串

程序员文章站 2022-05-24 23:29:36
...
public static String subStr(String str,int start,int end) throws Exception{
  byte[] bytes=str.getBytes("GBK");
  String  string="";
  end=end-start;
  if(start>=0&&end>0&&bytes.length>=(end+start)){
  if(start!=0){
  String tempString=new String(bytes,0,start,"GBK");
  String endTemp=tempString.substring(tempString.length()-1);
  String endTemp1=new String(endTemp.getBytes("GBK"),"GBK");
  if(endTemp.equals(endTemp1)){
  string= new String(bytes,start,end,"GBK");
  }else{
  string= new String(bytes,start+1,end-1,"GBK");
  }
  }else{
  string= new String(bytes,start,end,"GBK");
  }
  String laString=string.substring(string.length()-1);
  String lastTemp=new String(laString.getBytes("GBK"),"GBK");
  if(!laString.equals(lastTemp)){
  string=string.substring(0,string.length()-1);
  }
  }
  return string;
  }
相关标签: 截取字符串