gpt4 book ai didi

java - 在x个单词之后分割字符串

转载 作者:行者123 更新时间:2023-12-01 21:15:26 24 4
gpt4 key购买 nike

我有一个总是在变化的字符串,就像一个随机语句。我想要做的是在 10 个单词之后我想分割字符串,这样当我打印它时它是 2 行。

例如:

String s = "A random statement about anything can go here and it won't change anything."

然后我希望每十个单词就分割一次,所以在“it”之后它会被分割,然后它看起来像这样:

String[] arrayOfString;
System.out.println(arrayOfString[0]); -> which prints "A random statement about anything can go here and it"
System.out.println(arrayOfString[1]); -> which prints "won't change anything."

对此的任何帮助都会很棒,谢谢!

最佳答案

只是为了给你另一个解决方案。我认为这更容易阅读,因为它无需对数组进行索引操作即可工作:

package stack;

import java.util.StringTokenizer;

/**
* This class can Split texts.
*/
public class Splitter
{

public static final String WHITESPACE = " ";
public static final String LINEBREAK = System.getProperty("line.separator");

/**
* Insert line-breaks into the text so that each line has maximum number of words.
*
* @param text the text to insert line-breaks into
* @param wordsPerLine maximum number of words per line
* @return a new text with linebreaks
*/
String splitString(String text, int wordsPerLine)
{
final StringBuilder newText = new StringBuilder();

final StringTokenizer wordTokenizer = new StringTokenizer(text);
long wordCount = 1;
while (wordTokenizer.hasMoreTokens())
{
newText.append(wordTokenizer.nextToken());
if (wordTokenizer.hasMoreTokens())
{
if (wordCount++ % wordsPerLine == 0)
{
newText.append(LINEBREAK);
}
else
{
newText.append(WHITESPACE);
}
}
}
return newText.toString();
}
}

以及相应的 JUnit-Test,它使用 AssertJ-Library:

package stack;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;

public class SplitterTest
{
private final Splitter sut = new Splitter();

@Test
public void splitDemoTextAfter10Words() throws Exception
{
final String actual = sut.splitString(
"A random statement about anything can go here and it won't change anything.", 10);

assertThat(actual).isEqualTo("A random statement about anything can go here and it\r\n"
+ "won't change anything.");
}

@Test
public void splitNumerText() throws Exception
{

final String actual = sut.splitString("1 2 3 4 5 6 7 8 9 10 11 12", 4);

assertThat(actual).isEqualTo("1 2 3 4\r\n5 6 7 8\r\n9 10 11 12");
}
}

关于java - 在x个单词之后分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40265972/

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