将字符串字符分组为给定长度

时间:2016-06-02 11:53:38

标签: java arrays

我编写了一个简单的代码,将某个字符串分组为N长度,然后将其打印到控制台,其中字符组被" |"字符。有更简单的方法吗?顺便说一句,这是我的代码。

String d = "stackoverflow.com";
char[] x = d.toCharArray();
StringBuilder ad = new StringBuilder();
int r = 0;
int f = 6;
/*
f = 1; 2 characters by group
f = 2; 3 characters by group
...
f = n; (n+1) characters by group
*/
for (char a : x) {
    if (r == f) {
        ad.append(a);
        System.out.print(ad+"|");
        ad.delete(0, 1);
    } else {
        ad.append(a);
        r++;
    } 
}

其输出将为(f = 6)

stackov|tackove|ackover|ckoverf|koverfl|overflo|verflow|erflow.|rflow.c|flow.co|low.com|

1 个答案:

答案 0 :(得分:3)

如果将System.out包裹在PrintWriter中,则可以使用PrintWriter.write的重载来打印字符串的一部分:

PrintWriter pw = new PrintWriter(System.out, true);
for (int i = 0; i <= d.length() - f; ++i) {
  pw.write(d, i, f);
  pw.print('|');
}