java - 限制 Java 中 println() 语句的字符数

标签 java formatting string-formatting

我正在尝试实现一种方法,该方法接受一串文本和一列 宽度并输出文本,每行限制为列宽。

public void wrapText(String text, int width)
{
    System.out.println(text);
}

例如,用文本调用方法:

Triometric creates unique end user monitoring products for high-value Web 
  applications, and offers unrivalled expertise in performance consulting.

列宽为 20 的结果如下:

Triometric creates  
unique end user  
monitoring products  
for high-value Web  
applications, and  
offers unrivalled  
expertise in  
performance  
consulting.

最佳答案

你可以尝试这样的事情:

public static void wrapText(String text, int width) {
    int count = 0;

    for (String word : text.split("\\s+")) {
        if (count + word.length() >= width) {
            System.out.println();
            count = 0;
        }

        System.out.print(word);
        System.out.print(' ');

        count += word.length() + 1;
    }
}

尽管仍然存在该方法的结果不明确的情况(例如,如果单个单词的长度大于width)。上面的代码将简单地在它自己的行上打印这样一个词。

关于java - 限制 Java 中 println() 语句的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21048936/

相关文章:

wpf - 在 XAML 中向 Stringformat 添加换行符

java - java 中文件系统路径、文件名或 URI 操作的 Coverity 问题

java - 无法获取 ExtendedState JFrame 的大小

c - fprintf 语句中的\b 转义序列有问题..?

python - 在 GUI 记录器中添加颜色

python - ANSI 代码的字符串问题

java - Akka批量处理/单项处理

java - 读取 XML 并创建多个表

angular - 全局更改 Angular7 十进制格式

c# - StringFormat 在设计器中显示错误,但在编译后不显示