编写一个截取字符串的函数,输入一个字符串和字节数。然后输出字符串,要保证汉字不被截取半个,如:我ABC,4 应截取 “我AB”
首先要了解中文字符有多种编码及各种编码的特征 假设n为截取的字节数:
方法一、
public static void main(String[] args) {
String str="我ss是fs汗";
try {
byte[] B =str.getBytes("GBK");
int num=trimGBK(B, 4);
System.out.println(str.substring(0,num)); //根据substring按位数截取
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int trimGBK(byte[]buf,int n){
int num=0;
boolean bChineseFirestHalf=false;
for(int i =0;i<n;i++){
if(buf[i]<0&&!bChineseFirestHalf){
bChineseFirestHalf=true;
}else{
num++;
bChineseFirestHalf=false;
}
}
return num;
}
方法二、
class SplitString { private String str; private int byteNum; public SplitString() {} public SplitString(String str, int byteNum) { this .str = str; this .byteNum = byteNum; } public void splitIt() { byte bt[] = str.getBytes(); System.out.println( " Length of this String ===> " + bt.length); if (byteNum >= 1 ) { if (bt[byteNum] < 0 ) { String substrx = new String(bt, 0 , -- byteNum); System.out.println(substrx); } else { String substrex = new String(bt, 0 ,byteNum); System.out.println(substrex); } } else { System.out.println( " 输入错误!!!请输入大于零的整数: " ); } } } public class TestSplitString { public static void main(String args[]) { String str = " 我ABC汉DEF " ; int num = 6 ; SplitString sptstr = new SplitString(str,num); sptstr.splitIt(); }
方法 三:
/**
* 10、 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。
* 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
*
* @author 281167413@qq.com
*/
public class Test10 {
public static void main(String[] args) {
String srcStr1 = "我ABC";
String srcStr2 = "我ABC汉DEF";
splitString(srcStr1, 4);
splitString(srcStr2, 6);
}
public static void splitString(String src, int len) {
int byteNum = 0;
if (null == src) {
System.out.println("The source String is null!");
return;
}
byteNum = src.length();
byte bt[] = src.getBytes(); // 将String转换成byte字节数组
if (len > byteNum) {
len = byteNum;
}
// 判断是否出现了截半,截半的话字节对于的ASC码是小于0的值
if (bt[len] < 0) {
String subStrx = new String(bt, 0, --len);
System.out.println("subStrx==" + subStrx);
} else {
String subStrx = new String(bt, 0, len);
System.out.println("subStrx==" + subStrx);
}
}
}
本文介绍了一个使用Java实现的函数,用于截取包含中文的字符串,确保不会出现半个汉字被截断的情况。通过不同的方法,如GBK编码分析和字节长度判断,实现精确的截取功能。

7703

被折叠的 条评论
为什么被折叠?



