用Java语言编写一个方法,接受的输入为一个字符串和一个数字(最大长度)。这个函数会返回一个新的字符串,内容和输入的字符串一样,但是会在适当的地方加上一些换行符(\n),使得每一行的长度都不能超过输入的数字。换行符应该尽量位于单词之间,不要将完整的单词断开。
例如输入字符串为:
The function returns the string, but with line breaks inserted atjust the right places to make sure that no line is longer than the columnnumber.
最大长度为60,得到的结果应该是:
The function returns the string, but with line breaks\n
inserted at just the right places to make sure that no line\n
is longer than the column number.
代码如下
package com.example.LineFeed;
public class LineFeed {
public String makelinefeed(String s) {
//用空格作为分隔符,将单词存到字符数组里面
String[] str = s.split(" ");
//利用StringBuffer对字符串进行修改
StringBuffer buffer = new StringBuffer();
//判断单词长度,计算
int len = 0;
for (int i = 0; i < str.length; i++) {
//System.out.println(str);
//len = str[i].length();
//叠加
len += str[i].length();
//System.out.println(len);
if (len > 60) {
buffer.append("\n" + str[i] + " ");//利用StringBuffer对字符串进行修改
len = str[i].length()+1;//+1为换行后读出空格一位
//System.out.println(len);
} else {
buffer.append(str[i] + " ");
len++;
//System.out.println(len);
}
}
return buffer.toString();
}
public static void main(String[] args) {
LineFeed lf = new LineFeed();
System.out
.println(lf
.makelinefeed("The function returns the string, but with line breaks inserted at just the right places to make sure that no line is longer than the column number."));
}
}