/*
思路:
判断最后一个被截取的字节是不是负数。
如果是负数,继续往前判断,连续的负数的个数。
如果是偶数,说明没有半个中文。不用舍弃。
如果是奇数,说明有半个中文出现,舍弃最后一个字节。
*/
public class EncodeTest {
public static String cutString(String str,int len)throws Exception
{
byte[] buf = str.getBytes("GBK");
int count = 0;
for(int x=len-1; x>=0; x--)
{
if(buf[x]<0)
count++;
else
break;
}
if(count%2==0)
return new String(buf,0,len);
else
return new String(buf,0,len-1);
}
public static void main(String[] args) throws Exception {
String str = " 我abc汉字 ,6";
int len = 6; // 想要截取的长度,不管长度为几,都不会出现半个中文字符
System.out.println(cutString(str,len));
}
}
思路:
判断最后一个被截取的字节是不是负数。
如果是负数,继续往前判断,连续的负数的个数。
如果是偶数,说明没有半个中文。不用舍弃。
如果是奇数,说明有半个中文出现,舍弃最后一个字节。
*/
public class EncodeTest {
public static String cutString(String str,int len)throws Exception
{
byte[] buf = str.getBytes("GBK");
int count = 0;
for(int x=len-1; x>=0; x--)
{
if(buf[x]<0)
count++;
else
break;
}
if(count%2==0)
return new String(buf,0,len);
else
return new String(buf,0,len-1);
}
public static void main(String[] args) throws Exception {
String str = " 我abc汉字 ,6";
int len = 6; // 想要截取的长度,不管长度为几,都不会出现半个中文字符
System.out.println(cutString(str,len));
}
}