【发布时间】:2016-03-21 23:35:43
【问题描述】:
public class Ex7
{
//constructor
public static String s = "1234567890123456789 In the output words on a line are separated by precisely one space verb+' '+,\nlines are separated by\n\nprecisely one newline (so no trailing spaces) and";
public static int width = 20;
public static void format(){
StringBuilder sb = new StringBuilder();
for(int start = 0; start < s.length(); start += width){
int cursor = start + width - 1;
boolean w = true;
while(w){
if(cursor-1 < s.length()){
if((s.charAt(cursor) == ' ') || (s.charAt(cursor)== '\t')){
if(start + width -1 < s.length()){
sb.append(s.substring(start, cursor));
sb.append("\n");
w = false;
}
else{
sb.append("\n");
sb.append(s.substring(start));
w = false;
}
}
else{
cursor--;
}
}
else{
sb.append("\n");
sb.append(s.substring(start));
w = false;
}
}
}
System.out.println(sb);
}
}
大家好,
我的目标是格式化给定的 String s,以便在每 20 个字符之后有一个换行符(在这种情况下)。单词不能拆分(如果第 20 个字符是单词的一部分,则必须在该单词之前插入换行符。)
我的输出与这个示例字符串:
1234567890123456789
In the output words
on a line are
ted by precisely
space verb+'
nes are separated
precisely one
ine (so no trailing
spaces) and
锻炼想要的输出:
01234567890123456789
In the output words
on a line are
separated by
precisely one space
\verb+' '+, lines
are separated by
precisely one
newline (so no
trailing spaces)
and
我们不得使用 Scanner 类或第三方库。 有什么建议吗?
真诚地, FLiiX
【问题讨论】:
-
由于您不能在多行上拆分单词,最简单的方法是首先将输入字符串拆分为
String[],使用空格(在本例中为空格和换行符)作为分隔符;例如String[] words = s.split("\\s+");。完成此操作后,您可以简单地遍历words数组并将内容行附加到StringBuilder,记住每行 20 个字符的限制。
标签: java string newline stringbuilder