这是我的方法 仅供参考
方法一:
public class CutString{
public static void main(String[] args) throws Exception {
System.out.println(SubStringByByte("abc你好", 5));
}
public static String SubStringByByte(String str,int index)
{
if(index >= str.getBytes().length)
{
return str;
}
String temp = str;
for(int i = 0;i<str.length();i++)
{
if(temp.getBytes().length <= index)
{
break;
}
temp = temp.substring(0, temp.length() - 1);
}
return temp;
}
}
方法二:
package com.cg.test5;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
String string="abc你好呀,我真的很想进黑马!Hello";
int len=string.getBytes("utf-8").length;
for(int x=0;x<len;x++){
System.out.println("截取"+(x+1)+"个字节结果是:"+cutStringByU8Byte(string,x+1));
}
}
public static String cutStringByU8Byte(String str,int len) throws IOException{
byte [] buf=str.getBytes("utf-8");
int count=0;
for(int x=len-1;x>=0;x--){
if(buf[x]<0)
count++;
else {
break;
}
}
if(count%3==0)
return new String(buf,0,len,"utf-8");
else if(count%3==1)
return new String(buf,0,len-1,"utf-8");
else {
return new String(buf,0,len-2,"utf-8");
}
}
}
|