String[] for循環分割

public class Test {
    public static void main(String[] args) {
//        SystemCode systemCode = SystemCode.OK;
//        System.out.println(systemCode.getCode()+systemCode.getMessage());
//        String encodeStr= DigestUtils.md5Hex("123456");
//        System.out.println(encodeStr);
        String arr[] = new String[]{"a", "b", "c", "d", "e", "f","g"};
        splitArr( arr, 2 );


      輸出結果展示:
       a,b
       c,d
       e,f
       g
   }


//arraycopy  參數分別是:源數組,源數組開始截取的位置,目標數組,目標數組開始生成數據的位置,目標數組的長度
public static void splitArr(String arr[], int splitSize) {
    int a = arr.length / splitSize;
    if (a == 0) {
        System.out.println( transform( arr ) );
    } else {
        for (int i = 0; i <= a; i++) {
            if (i < a) {
                String narr[] = new String[splitSize];
                System.arraycopy( arr, i * splitSize, narr, 0, splitSize );
                System.out.println( transform( narr ) );
            } else {
                if (arr.length!=i*a) {
                    String narr[] = new String[arr.length - a * splitSize];
                    System.arraycopy( arr, a * splitSize, narr, 0, arr.length - a * splitSize );
                    System.out.println( transform( narr ) );
                }
            }

        }
    }
}

public static String transform(String[] arr) {
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < arr.length; i++) {

        if (i < arr.length - 1) {
            stringBuffer.append( arr[i] + "," );
        } else {
            stringBuffer.append( arr[i] );
        }
    }
    return stringBuffer.toString();
}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章