如何在一定线长后进入新线?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在一定线长后进入新线?相关的知识,希望对你有一定的参考价值。

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

当前代码(它是一个烂摊子,我尝试了许多其他帖子的不同解决方案)

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
		    ");
                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,
答案

如果你构建一个字符串会更容易,只有当你超过行长时才打印它。不要munge 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

以上是关于如何在一定线长后进入新线?的主要内容,如果未能解决你的问题,请参考以下文章

React Native:如何检测应用程序是不是在启动时/从 AppSwitcher 关闭应用程序后进入前台?

电脑是苹果m1芯片的,安装的pd虚拟机 win 11 安装好后进入win 系统安装不了软件?

如何制作溢出后进入下一行的列表视图,并且只有一个项目应该是可选的

如何修复docker在ubuntu上docker-compose后进入重启状态的问题?

从 Pycharm 控制台调用函数后进入调试模式

百度云推送点击通知后进入不了想要的页面