写一个方法,有两个参数,一个是待截取的字符串,另一个是要截取的字节数,返回截取后的字符串,要求返回的字符串中的中文不能出现乱码。如:("我ABC",4)应该截取为“我AB”。
输入(“我ABC汗DEF”,6)应该截取为“我ABC”而不是“我ABC+汗的半个”。别忘了写注释哈。

解决方案 »

  1.   

    才看到过一个帖子 就csdn上!
      

  2.   

    给个方法给你看看。public class Test { public static void main(String[] args) {
    mySplit("我ABC", 4);
    mySplit("我ABC汗DEF", 6);
    } /*
     * 写一个方法,有两个参数,一个是待截取的字符串,另一个是要截取的字节数,返回截取后的字符串, 要求返回的字符串中的中文不能出现乱码。
     * 如:("我ABC", 4)应该截取为“我AB”。
     * 输入(“我ABC汗DEF”,6)应该截取为“我ABC”而不是“我ABC+汗的半个”。别忘了写注释哈。
     */
    private static void mySplit(String str, int count) { byte[] temp = str.getBytes();
    byte[] bArray = new byte[count * 2]; int i;
    int ii = 0;// 用于判断最后一个是不是一半汉字
    String strc = "full"; for (i = 0; i < count; i++) {
    bArray[i] = temp[i];
    }
    for (i = 0; i < count; i++) {
    if (bArray[i] < 0) {
    ii++;
    }
    }
    if (ii % 2 != 0) {
    strc = "hard";
    } // 截下去为完全的时候
    if (strc.equals("full") && bArray[i] < 0) {
    bArray[i] = ' ';
    }
    // 截下去为一半的时候
    if (strc.equals("hard") && bArray[i - 1] < 0) {
    bArray[i - 1] = ' ';
    }
    System.out.println(new String(bArray).trim());
    }}
      

  3.   

    一个简单的方法: public static void getChar(String str, int count) {
    byte[] byteArray = new byte[count];
    byte[] temp = str.getBytes();
    int ii = 0;
    for (int i = 0; i < count; i++) {
    byteArray[i] = temp[i];
    if (temp[i] < 0) {
    ii++;
    }
    }
    if (ii % 2 == 1) {
    byteArray[count - 1] = ' ';
    }
    System.out.println(new String(byteArray).trim()); }