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;
}
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;
}
上一篇: 含有中英文的字符串截取
下一篇: Android截取字符串