如何在某个点切断一条线,但在最近的空间处分割

How to have a line cut off at a certain point but split at the nearest space

提问人:Nick Slack 提问时间:3/8/2023 更新时间:3/8/2023 访问量:50

问:

我希望每行在经过 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

比你提供任何帮助。

java for 循环 子字符串 java.util.scanner

评论

0赞 PM 77-1 3/8/2023
我建议你把行拆成字,然后打印这些字,直到长度总和超过你的限制。您将需要两个嵌套循环。

答:

2赞 phatfingers 3/8/2023 #1

您可以采取的一种方法是:

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
}

评论

0赞 Nick Slack 3/8/2023
我知道我要求澄清已经晚了,但是您将 startPos 移动到 endPos+1 是什么意思
0赞 phatfingers 3/8/2023
简单来说就是startPos = endPos + 1;
0赞 phatfingers 3/8/2023
例如,如果你的句子是 50 个字符,你的循环将根据你的新 startPos + 20 + 到下一个空格(或字符串结尾,以先到者为准)的距离来确定一个新的 endPos
1赞 WJS 3/8/2023 #2

这是一种方式。

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;
  • 分配 a 来保存子字符串List
  • 循环,直到该行为 或剩余段小于blanksize
  • 现在检查字符中是否有从大小小于 1 开始的空格。
  • 将该子字符串添加到列表中,并将该行更新到下一个起始位置。
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;
}