有一列字符串,如String s=“说sg收a”有7个字节,中文占二个字节。
将该列字符按每行有相应的字符输出,如果某一行的最后的一个字符的中文被拆开,则将其放在下一行输出。
如:String s="收sds到sfq都是sk是";按每行6个字符输出的话:则结果为:
第一行为:收sds
第二行为:到sfq
第三行为:都是sk
第四行为:是

解决方案 »

  1.   

    这个题目有点叼public class TestString {
    public void outputString(String str,int i){
    int count=0;
    StringBuffer sb=new StringBuffer("");
    char[] c=str.toCharArray();
    if(i==0){
    System.out.println(str);
    }
    if(i==1&&c[0]>255){
    System.out.println("第一个字符是汉字,无法分割");
    System.exit(0);
    }
    else{
    for(int j=0;j<i;j++){
    if(c[j]>255&&(i-count)>1){
    count=count+2;
    sb.append(c[j]);
    }
    else if(c[j]<255&&(i-count)>0){
    count=count+1;
    sb.append(c[j]);
    }
    else break;
    }
    }
    System.out.println(sb);
    int index=sb.length();
    outputString(str.substring(index), i);
    }
    public static void main(String[] args){
    TestString ts=new TestString();
    ts.outputString("收sds到sfq都是sk是",6);
    }
    }
      

  2.   


    String s = "收sds到sfq都是sk是";

    Pattern p = Pattern.compile("([\\u4e00-\\u9fa5]+[\\w]*)");
    Matcher m = p.matcher(s);

    while(m.find()) {
    System.out.println(m.group());
    }
      

  3.   

    把昨天晚上的代码改了下,可以满足你的要求了public class TestString {
    public int getTotalByte(char[] c) {
    int totalBytes = 0;
    for (int i = 0; i < c.length; i++) {
    if (c[i] > 255) {
    totalBytes = totalBytes + 2;
    }
    if (c[i] < 255) {
    totalBytes = totalBytes + 1;
    }
    }
    return totalBytes;
    } public void outputString(String str, int i) {
    int count = 0;
    StringBuffer sb = new StringBuffer();
    char[] c = str.toCharArray();
    int totalbytes = getTotalByte(c);
    if (i <= totalbytes) {
    for (int j = 0; j < i; j++) {
    if (c[j] > 255 && (i - count) > 1) {
    count = count + 2;
    sb.append(c[j]);
    } else if (c[j] < 255 && (i - count) > 0) {
    count = count + 1;
    sb.append(c[j]);
    } else
    break;
    }
    System.out.println(sb);
    int index = sb.length();
    outputString(str.substring(index), i);

    if(i>totalbytes){          //避免数组越界的判断
    System.out.println(str);
    }
    } public static void main(String[] args) {
    TestString ts = new TestString();
    ts.outputString("收sds到sfq都是sk是", 6);
    System.out.println("-------------------------------");
    ts.outputString("收sds到sfq都是sk是", 5);
    System.out.println("-------------------------------");
    ts.outputString("收sds到sfq都是sk是", 7);
    }
    }