gpt4 book ai didi

java - 在java中将大字符串拆分为最大长度的行

转载 作者:IT老高 更新时间:2023-10-28 20:56:27 26 4
gpt4 key购买 nike

String input = "THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, www.nationalgeographic.com, which includes but is not limited to products, software and services offered by way of the website such as the Video Player, Uploader, and other applications that link to these Terms (the Site). Please review the Terms fully before you continue to use the Site. By using the Site, you agree to be bound by the Terms. You shall also be subject to any additional terms posted with respect to individual sections of the Site. Please review our Privacy Policy, which also governs your use of the Site, to understand our practices. If you do not agree, please discontinue using the Site. National Geographic reserves the right to change the Terms at any time without prior notice. Your continued access or use of the Site after such changes indicates your acceptance of the Terms as modified. It is your responsibility to review the Terms regularly. The Terms were last updated on 18 July 2011.";

//text copied from http://www.nationalgeographic.com/community/terms/

我想把这个大字符串分成几行,每行的内容不应超过 MAX_LINE_LENGTH 个字符。

到目前为止我尝试了什么

int MAX_LINE_LENGTH = 20;    
System.out.print(Arrays.toString(input.split("(?<=\\G.{MAX_LINE_LENGTH})")));
//maximum length of line 20 characters

输出:

[THESE TERMS AND COND, ITIONS OF SERVICE (t, he Terms) ARE A LEGA, L AND B ...

它会导致断词。我不想要这个。而不是我想得到这样的输出:

[THESE TERMS AND , CONDITIONS OF , SERVICE (the Terms) , ARE A LEGAL AND B ...

又添加了一个条件:如果单词长度大于 MAX_LINE_LENGTH,则该单词应该被拆分。

并且解决方案应该没有外部 jar 的帮助。

最佳答案

只需逐字遍历字符串并在单词超过限制时中断。

public String addLinebreaks(String input, int maxLineLength) {
StringTokenizer tok = new StringTokenizer(input, " ");
StringBuilder output = new StringBuilder(input.length());
int lineLen = 0;
while (tok.hasMoreTokens()) {
String word = tok.nextToken();

if (lineLen + word.length() > maxLineLength) {
output.append("\n");
lineLen = 0;
}
output.append(word);
lineLen += word.length();
}
return output.toString();
}

我只是徒手输入的,您可能需要稍微插入一下才能使其编译。

Bug:如果输入中的单词长于 maxLineLength,它将被附加到当前行而不是它自己的太长的行。我假设您的行长大约是 80 或 120 个字符,在这种情况下这不太可能成为问题。

关于java - 在java中将大字符串拆分为最大长度的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7528045/

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