Java按字节截取字符串(GBK编码、UTF-8编码实现)

时间:2023-03-09 10:01:04
Java按字节截取字符串(GBK编码、UTF-8编码实现)
 package FileDemo;

 import java.io.IOException;

 public class CutStringTest {

     /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException { String str = "ab你好cd谢谢";
/*byte buf[]=str.getBytes("GBK");
for(byte ch:buf){
System.out.println(Integer.toBinaryString(ch));
}*/
int len = str.getBytes("gbk").length;
for (int x = 0; x < len; x++) {
System.out.println("截取" + (x + 1) + "字节结果时:"
+ cutStringByByte(str, x + 1));
}
String str1 = "ab你好cd杮";
int len1 = str.getBytes("gbk").length;
for (int x = 0; x < len1; x++) {
System.out.println("截取" + (x + 1) + "字节结果时:"
+ cutStringByU8(str1, x + 1));
}
} // 使用UTF-8编码表进行截取字符串,一个汉字对应三个负数,一个英文字符对应一个正数
private static String cutStringByU8(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");
}
} // 使用GBK编码表进行字符串的截取,一个英文字符对应码表一个正数,一个汉字对应两个负数
public static String cutStringByByte(String str, int len)
throws IOException {
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, "gbk");
} else {
return new String(buf, 0, len - 1, "gbk");
}
} }