package com.heping.xx;
//7、编程:编写一个截取字符串的函数,输入为一个字符串和字节数,
//输出为按字节截取的字符串。 但是要保证汉字不被截半个,
//如"我ABC"4,应该截为"我AB",输入"我ABC汉DEF",6,
//应该输出为"我ABC"而不是"我ABC+汉的半个"。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class ByteSelect {
private String str;
private int byteNum;
public ByteSelect() { }
public ByteSelect(String str, int byteNum) {
this.str = str;
this.byteNum = byteNum;
}
public void splitIt() {
// str = "我ABC汉DEF";
// 12345678910
byte bt[] = str.getBytes();
// System.out.println("now,bytes.."+bt);
System.out.println("Length of this String ===>" + bt.length);
if (byteNum > 1) {
System.out.println("byteNum==" + bt[byteNum]);
//如果当前字节下一位小于0,说明当前截取位置将中文字符截断了
if (bt[byteNum] < 0) {
System.out.println("1\\" + bt[byteNum]);
String substrx = new String(bt, 0, --byteNum);//当前被截断的中文字符整个不取
System.out.println("substrx=" + substrx);
} else {
//当前字节下一位大于0,说明当前位置起码不是截断的中文字符中间位
System.out.println("2\\" + bt[byteNum]);
String substrex = new String(bt, 0, byteNum);
System.out.println(substrex);
}
} else {
if (byteNum == 1) {
System.out.println("byteNum==" + bt[byteNum]);
if (bt[byteNum] < 0) {
String substr1 = new String(bt, 0, ++byteNum);
System.out.println("substr1" + substr1);
} else {
String subStr2 = new String(bt, 0, byteNum);
System.out.println("subStr2" + subStr2);
}
} else {
System.out.println("输入错误!!!请输入大于零的整数:");
}
}
}
}
public class Heping {
public static void main(String args[]) throws NumberFormatException,
IOException {
String str = "我ABC汉DEF";
System.out.println("pls input:");
int num = Integer.parseInt(new BufferedReader(new InputStreamReader(
System.in)).readLine());
ByteSelect sptstr = new ByteSelect(str, num);
sptstr.splitIt();
// byte[] b = str.getBytes();
// for(int i=0;i<b.length;i++)
// System.out.println(b[i]);
// System.out.println("1.."+new String(b,0,6));
// System.out.println("2.."+new String(b,0,7));
// System.out.println("3.."+new String(b,0,1));
// System.out.println("4.."+new String(b,0,2));
// System.out.println("2.."+new String(b,0,7));
}
}