我正在尝试实现一种方法,该方法接受一串文本和一列 宽度并输出文本,每行限制为列宽。
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/