gpt4 book ai didi

java - 通过 maxLines 参数和字符数剪切字符串

转载 作者:行者123 更新时间:2023-11-30 06:23:36 25 4
gpt4 key购买 nike

我正在编写一个类,其方法接受摘要字符串并将其分解为最大行数(maxLines 参数)和每行最大字符数(width 参数)。除第一行外的所有行都应缩进(应以空格字符开头),但缩进行中的第二个字符不应是另一个空格(因此不得包含第二个空格)。如果更改 maxLine 参数 r 宽度,程序应该仍然可以工作。

此外,代码应该检查字符串中是否存在某些特殊字符,例如:

 \' , \" , \\ , \t , \b , \r , \f , \n 

如何检查字符串中是否有很多空格,如下所示?如果字符串中有很多空格,我想修剪它们,但我不知道该怎么做。 (这些下划线代表空格。)

"9:00 John_____________________________Doe until 10 30 at Office"

9:00 Jo
_hn____
_______
_____Do

使用我的代码,我得到这个结果:

 9:00 Jo
_hn Doe
_until 1
_0 30 at

但我想要这个输出:

9:00 Jo
_hn Doe
_until_
_10 30_

这是我的代码:

public static void main(String[] args) {

String str = "9:00 John Doe until 10 30 at Office";
int width = 7;
int maxLine = 4;
List<String> lisT = new LinkedList<>(getParts(str, width, maxLine));
for (String part : lisT) {
System.out.println(part);
}
}

public static List<String> getParts(String str, int width, int maxLine) {
List<String> parts = new LinkedList<>();
int count = 0;
int len = str.length();
String indent = "";
for (int i = 0; i < len; i += width) {
parts.add(indent + str.substring(i, Math.min(len, i + width)).trim());
count++;
indent = " ";
if (count == maxLine)
break;
}
return parts;
}

最佳答案

这就是你想要的吗?我真的希望你不必在某些东西中实现这个,因为我必须破坏它才能使其工作。希望这是家庭作业

public static void main(String[] args) {
String str = "9:00 John Doe until 10 30 at Office";
int width = 7;
int maxLine = 4;
List<String> lisT = new LinkedList<>(getParts(str, width, maxLine));
for (String part : lisT) {
System.out.println(part);
}
}

public static List<String> getParts(String str, int width, int maxLine){
List<String> parts = new LinkedList<>();
int endedAt = 0;
boolean firstLine = true;
boolean secondLine = true;
String indent = " ";
for (int i = 0; i < maxLine; i++) {
if(endedAt<=str.length()) {
String holder;
if(firstLine) {
holder = str.substring(endedAt, endedAt + width);
firstLine = false;
}
else {
if(secondLine){
width = width -1;
secondLine = false;
}
holder = indent + str.substring(endedAt, endedAt + width).trim();
}
parts.add(holder);
endedAt = endedAt + width;
}
}
return parts;
}

输出为

9:00 Jo
hn Doe
until
10 30

关于java - 通过 maxLines 参数和字符数剪切字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47661121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com