gpt4 book ai didi

java - 使用适当的换行将长字符串分成几行

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:31:17 25 4
gpt4 key购买 nike

 String original = "This is a sentence.Rajesh want to test the application for the word split.";
List matchList = new ArrayList();
Pattern regex = Pattern.compile(".{1,10}(?:\\s|$)", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(original);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
System.out.println("Match List "+matchList);

我需要将文本解析为长度不超过 10 个字符的行数组,并且行尾不应有断行符。

我在我的场景中使用了以下逻辑,但问题是如果行尾有中断,它会在 10 个字符后解析到最近的空白

例如:实际的句子是“This is a sentence.Rajesh want to test the application for the word split.”但是在逻辑执行之后它得到如下。

匹配列表 [这是一个 , nce.Rajesh ,想要 , 测试 , 应用程序 , 对于 , word , split。]

最佳答案

好的,所以我已经成功地完成了以下工作,最大行长度为 10,而且还正确地拆分了超过 10 的单词!

String original = "This is a sentence. Rajesh want to test the applications for the word split handling.";
List matchList = new ArrayList();
Pattern regex = Pattern.compile("(.{1,10}(?:\\s|$))|(.{0,10})", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(original);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
System.out.println("Match List "+matchList);

这是结果:

This is a 
sentence.
Rajesh want
to test
the
applicatio
ns word
split
handling.

关于java - 使用适当的换行将长字符串分成几行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10702367/

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