我希望每行在 20 个字符过去后分开,但我希望它在最近的空间分开,所以句子只有完整的单词。
这是我的代码:
System.out.println("Please input a word: ");
Scanner stringScanner = new Scanner(System.in);
String input = stringScanner.nextLine();
int numberOfCharacters = 20;
for(int pos = numberOfCharacters; pos >= 0; pos --)
{
if(input.charAt(pos) == ' ')
{
System.out.println(input.substring(0, pos));
System.out.println(input.substring(pos+1,21));
}
}
}
}
这是我得到的输出,不知道为什么:
请输入字词:
Hello there, I am doing some coding, I need some help
Hello there, I am
doi
Hello there, I
am doi
Hello there,
I am doi
Hello
there, I am doi
The output I want is:
Hello there, I am
doing some coding,
I need some help
谢谢你的帮助。
您可以采取的一种方法是:
str="some long string"
while (str can be safely split) {
split off and print the left portion
assign the right portion to str
}
print the remainder of str
如果你不想改变输入和管理位置,使用两个变量会更简单,一个 startPos 和一个 endPos。
str="some long string"
startPos=0, endPos=0
while (startPos < str.length) {
determine endPos
print substring from startPos to endPos
move startPos to endPos+1
}
这是一种方法。
String str = "What's in a name? That which we call a rose "
+ "By any other name would smell as sweet;";
List<String> list = splitLine(str, 20);
list.forEach(System.out::println);
版画
What's in a name?
That which we call
a rose By any other
name would smell as
sweet;
List
来保存子字符串blank
或者如果剩余的段小于size
public static List<String> splitLine(String line, int size) {
List<String> list = new ArrayList<>();
while (!line.isBlank()) {
int len = Math.min(line.length(), size);
if (len < size) {
list.add(line);
break;
}
while (line.charAt(--len) != ' ') {
if (len == 0) {
throw new
IllegalArgumentException("\nWord length exceeds size specification");
}
}
list.add(line.substring(0, len));
line = line.substring(len+1);
}
return list;
}