程序要求:
编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
实现:
class SplitString {
String SplitStr;
int SplitByte;
public int curByteCount = 0;
public SplitString(String str, int bytes) {
SplitStr = str;
SplitByte = bytes;
System.out.println("The String is:'" + SplitStr + "';SplitBytes="
+ SplitByte);
}
/**
* 截取字符串
*/
private void splitString() {
StringBuffer bf = new StringBuffer();
for (int i = 0; i < SplitStr.length(); i++) {
char temp = SplitStr.charAt(i);
String s = new String(new char[]{temp});
if(s.getBytes().length==s.length()){
curByteCount++;
}
else{
curByteCount += 2;
}
if (curByteCount > SplitByte) {
break;
} else {
bf.append(temp);
}
}
System.out.println(bf);
}
public static void main(String[] args) {
SplitString ss = new SplitString("我abcd好", 7);
ss.splitString();
}
基本思想:取得字符串中的char,如果是中文标识变量curByteCount +=2。否则curByteCount++,当curByteCount 大于要截取得byte长度,跳出循环,得到字符串。