java - 使用换行符将字符串中的行限制为 60 个字符
问题描述
该程序用于从字符串中删除双倍、三倍……空格,并将字符限制为每行 60 个。
问题是当想法是它必须跳过它们时,它会将单词放入第 60 位的行中。
输出是:
Java was originally developed by James Gosling at Sun Microsystems
(which has since been acquired by Oracle) and released in 1995
as a core component of Sun Microsystems' Java platform.
但正确的输出必须是:
Java was originally developed by James Gosling at Sun
Microsystems (which has since been acquired by Oracle) and
released in 1995 as a core component of Sun Microsystems'
Java platform.
到目前为止我的代码:
StringBuilder sb = new StringBuilder(text.replaceAll("(^ )|( $)", "").replaceAll("\\s{2,}", " "));
int i = 0;
while ((i = sb.indexOf(" ", i + 60)) != -1) {
sb.replace(i,i+1,"\n");
}
String result = sb.toString();
return result;
}
解决方案
这是我第 24 次试运行的结果。
Java was originally developed by James Gosling at Sun Microsystems
(which has since been acquired by Oracle) and released in 1995
as a core component of Sun Microsystems' Java platform.
Java was originally developed by James Gosling at Sun
Microsystems (which has since been acquired by Oracle) and
released in 1995 as a core component of Sun Microsystems'
Java platform.
第一段是输入。第二段是输出。
看一下代码。你看到几个被注释掉的System.out.println
语句吗?这就是您发现代码问题的方式。您编写几行代码,然后打印中间结果。冲洗并重复,直到您的代码有效。
这是完整的可运行代码。
public class FixedLengthLines {
public static void main(String[] args) {
new FixedLengthLines().processString();
}
public void processString() {
String text = "Java was originally developed by James Gosling at Sun Microsystems\r\n" +
"(which has since been acquired by Oracle) and released in 1995\r\n" +
"as a core component of Sun Microsystems' Java platform.";
String temp = text.replaceAll("\\s{2,}", " ");
// System.out.println(temp);
int lineLength = 60;
int lineIndex = 0;
int endIndex = Math.min(lineIndex + lineLength, temp.length());
StringBuilder builder = new StringBuilder();
while (lineIndex < endIndex) {
// System.out.println(lineIndex + " " + endIndex + " " + temp.length());
if (endIndex >= lineIndex + lineLength) {
endIndex = temp.lastIndexOf(" ", endIndex);
}
builder.append(temp.substring(lineIndex, endIndex));
builder.append(System.lineSeparator());
// System.out.println(endIndex + " " + temp.substring(lineIndex, endIndex));
lineIndex = endIndex + 1;
endIndex = Math.min(lineIndex + lineLength, temp.length());
}
System.out.println(text);
System.out.println();
System.out.println(builder.toString());
}
}
推荐阅读
- java - 尽管运行代码以显示菜单,Java 小程序仍显示白屏
- google-sheets - 如何从索引中的数组公式返回日期值:匹配公式(左/右函数)
- class - UML 类图:依赖于两个类的属性和方法
- javascript - 如何解码base64解码文件并保存为pdf文件
- python-3.x - 无法将 python 列表中的第二项(路由器命令)传递给网络设备
- scala - 我什么时候需要在 scala 中向我的类添加成员定义?
- c# - 在 MVVM 中,我如何将模型中的列表绑定到组合框?
- python - Keras 中的相同工作模型在 Pytorch 中没有得到改进
- unity3d - Unity 无法从自定义程序集定义中看到 Assembly-CSharp.dll 程序集中的脚本
- regex - 如何创建将查找复杂 URL 的子字符串的正则表达式