一、题目分析
保证汉字不被截半个:把字符串转换为byte[] bt ,中文会被转换成负数,即bt[i]<0说明是中文
二、代码
我这里使用“GBK”编码格式,即一个中文占2个字节
package test;
import java.io.UnsupportedEncodingException;
/**
* 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。
* 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6, 应该输出为“我ABC”而不是“我ABC+汉的半个”。
*
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
String str1 = "我AB";
String str2 = "我ABC汉DEF";
String str3 = "";
String str4 = "云筝是AB";
System.out.println("splitString(\"我AB\", 4):" + splitString(str1, 4));
System.out.println("splitString(\"我ABC汉DEF\", 6):" + splitString(str2, 6));
System.out.println("splitString(\"\", 4):" + splitString(str3, 4));
System.out.println("splitString(\"云筝是AB\", 5):" + splitString(str4, 5));
}
public static String splitString(String str, int len) {
if (str == null) {
return "The source String is null!";
}
try {
// 把字符串按照“GBK”编码转换为byte[],即一个中文2个字节,按题目要求来吧
byte[] bt = str.getBytes("GBK");
int btLength = bt.length;
byte[] result = new byte[btLength];
if (len >= bt.length) { // 如果所截长度大于或等于字节数组,即截取全部
return new String(bt, "GBK");
}
for (int i = 0; i < len; i++) {
if (bt[i] >= 0) {
result[i] = bt[i];
}
// bt[i]<0代表是中文
else if (++i < len && bt[i] < 0) // 判断是否截半
{
result[--i] = bt[i];// i的计算是从左到右
result[++i] = bt[i];
} else {
return new String(result, "GBK");
}
}
return new String(result, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "出现异常";
}
}
}
三、输出结果