gpt4 book ai didi

java - 如何截断一定长度的字符串但截断后包含完整的单词

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:08 26 4
gpt4 key购买 nike

我想从最多 60 个字符的字符串中截断子字符串,但也想在子字符串中获取完整的单词。这就是我正在尝试的。

String originalText =" Bangladesh's first day of Test cricket on Indian soil has not been a good one. They end the day having conceded 71 runs in the last 10 overs, which meant they are already staring at a total of 356. M Vijay was solid and languid as he made his ninth Test century and third of the season. ";
String afterOptimized=originalText.substring(0, 60);
System.out.println("This is text . "+afterOptimized);

这里是输出

This is text .  Bangladesh's first day of Test cricket on Indian soil has n

但是我的要求是不能把中间的单词截断,怎么知道60个字符后有没有完整的单词。

最佳答案

您可以为此使用正则表达式,最多 60 个字符并以单词边界结束:

Pattern pattern = Pattern.compile("(.{1,60})(\\b|$)(.*)");
Matcher m = pattern.match(originalText);
If (m.matches())
afterOptimized = m.group(1);

或者,在一个循环中:

Pattern pattern = Pattern.compile("\\s*(.{1,60})(\\b|$)");
Matcher m = pattern.matcher(originalText);
int last = 0;
while (m.find()) {
System.out.println(m.group(1));
last = m.end();
}
if (last != originalText.length())
System.out.println(originalText.substring(last));

如果你只想在空白而不是单词边界处换行(可能在逗号、点等之前换行),你可能想用 \s 替换 \b .

关于java - 如何截断一定长度的字符串但截断后包含完整的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42150571/

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