输出为按字节截取的字符串。 但是要保证汉字不被截半个,
如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
*/
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) {
pBinInt("bt[byteNum]", bt[byteNum]);
System.out.println("bt[" + byteNum + "] = " + bt[byteNum]);// 1
System.out
.println("bt[" + byteNum + "] = " + (int) bt[byteNum]);// 2
System.out.println("bt[" + byteNum + "] = "
+ (bt[byteNum] & 0x000000FF));// 3
System.out.println("bt[" + byteNum + "] = "
+ (bt[byteNum + 1] & 0XFF));// 4
String substrx = new String(bt, 0, --byteNum);
System.out.println(substrx);
} else {
String substrex = new String(bt, 0, byteNum);
System.out.println(substrex);
}
} else {
if (byteNum == 1) {
if (bt[byteNum] < 0) {
String substr1 = new String(bt, 0, --byteNum);
System.out.println(substr1);
} else {
String subStr2 = new String(bt, 0, byteNum);
System.out.println(subStr2);
}
} else {
System.out.println("输入错误!!!请输入大于零的整数:");
}
}
}
static void pBinInt(String s, int i) {
System.out.println(s + ", int: " + i + ", binary: ");
System.out.print(" ");
for (int j = 31; j >= 0; j--)
if (((1 << j) & i) != 0)
System.out.print("1");
else
System.out.print("0");
System.out.println();
}
}
class TestSplitString {
public static void main(String args[]) {
String str = "我abc的DEFe";
int num = 6;
SplitString sptstr = new SplitString(str, num);
sptstr.splitIt();
}
}