一定的线长后如何去换行?

时间:2018-09-02 22:34:37

标签: java arrays string formatting

我有一个数组,在达到某个字符限制后需要换行,但是我不希望它切断数字。我尝试将数组转换为字符串以除去括号和空格,但似乎无法在正确的位置将字符串换成新的一行。我该如何完成?谢谢!

当前代码(我已经尝试了其他文章提出的许多不同解决方案,这是一团糟)

System.out.println(n + " (" + numDivisors + " proper divisors)");
    System.out.print("...proper divisors: ");

    String temp = Arrays.toString(properDivisors).replace("]", ",").replace(" ", "");
    String finalDiv = temp.substring(1, temp.length());
    if (finalDiv.length() > len) {
        for (int i = len; i <= len; i--){
            if (finalDiv.charAt(len) == ',') {
                finalDiv = finalDiv.replaceAll(".{" + i + "}", "$0\n\t\t    ");
                System.out.print(finalDiv);
            }
        }
    } else {
        System.out.println(finalDiv);
    }

所需的输出

86268 (47 proper divisors)                                                               
...proper divisors: 1,2,3,4,6,7,12,13,14,21,26,28,39,42,52,78,79,84,91,
                    156,158,182,237,273,316,364,474,546,553,948,1027,
                    1092,1106,1659,2054,2212,3081,3318,4108,6162,6636,
                    7189,12324,14378,21567,28756,43134,

1 个答案:

答案 0 :(得分:0)

如果您构建一个字符串,并且仅在超过行长时才打印它,这将变得更加容易。请勿修改Arrays.toString(),只需自己构建字符串表示形式即可。

String prefix = "...proper divisors: ";
// Same number of chars as prefix, just all spaces.
String emptyPrefix = prefix.replaceAll(".", " ");
for (int i = 0; i < properDivisors.length;) {

  // Take as many of the items in the array as you can, without exceeding the
  // max line length.
  StringBuilder sb = new StringBuilder(prefix);
  for (; i < properDivisors.length; ++i) {
    int lengthBefore = sb.length();

    // Append the next item, and comma, if it would be needed.
    sb.append(properDivisors[i]);
    if (i + 1 < properDivisors.length) sb.append(",");

    if (sb.length() > maxWidth) {
      // Truncate back to the length before appending.
      sb.setLength(lengthBefore);
      break;
    }
  }
  System.out.println(sb);

  // Blank out the prefix, so you will print leading spaces on next line.
  prefix = emptyPrefix;
}

Ideone demo