我正在尝试实现一种方法,该方法需要文本字符串和列
宽度并输出文本,每行限制为列宽。
public void wrapText(String text, int width)
{
System.out.println(text);
}
例如,使用文本调用该方法:
Triometric为高价值Web创建独特的最终用户监视产品
应用程序,并在性能咨询方面提供无与伦比的专业知识。
宽度为20的列将导致以下输出:
三角创建
唯一的最终用户
监控产品
用于高价值的网站
应用程序,以及
提供无与伦比的
专业知识
性能
咨询。
最佳答案
您可以尝试如下操作:
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
)。上面的代码将仅在自己的行上打印这样的单词。