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

时间:2016-10-26 15:12:00

标签: java split

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

例如:

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

然后我希望每十分之一被分开,所以在'它'之后它会被拆分然后看起来像这样:

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."

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

3 个答案:

答案 0 :(得分:1)

以下是代码:代码假定您最多分为10次,也可以分为Integer.MAX_VALUE

public static void main(String[] args) {
    String s = "A random statement about anything can go here and it won't change anything.";
    int spaceCount =0;
    int lastIndex=0;
    String[] stringSplitted = new String[10];//assuming the sentence has 100 words or less, you can change the value to Integer.MAX_VALUE instead of 10


    int stringLength=0;//this will give the character count in the string to be split

    for(int i=0;i<s.length();i++){
        if(s.charAt(i)==' '){   //check whether the character is a space, if yes then count the words           
            spaceCount++;// increment the count as you have encountered a word              
        }
        if(spaceCount==10){     //after encountering 10 words split the sentence from lastIndex to the 10th word. For the first time lastIndex would be zero that is starting position of the string        
            stringSplitted[stringLength++] = s.substring(lastIndex, i);
            lastIndex=i;// to get the next part of the sentence, set the last index to 10th word
            spaceCount=0;//set the number of spaces to zero to starting counting the next 10 words
            System.out.println(stringSplitted[0]);
        }
    }
    stringSplitted[stringLength++] = s.substring(lastIndex,s.length()-1);//If the sentence has 14 words, only 10 words would be copied to stringSplitted array, this would copy rest of the 4 words into the string splitted array

    for(int i=0;i<stringSplitted.length;i++){
        if(stringSplitted[i]!=null)
            System.out.println(stringSplitted[i]);//Print the splitted strings here
    }

}

答案 1 :(得分:1)

只是为了给你另一个解决方案。我认为这更容易阅读,因为它在数组上没有索引操作的情况下工作:

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();
   }
}

使用AssertJ-Library的相应的JUnit-Test:

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");
  }
}

答案 2 :(得分:1)

另一种解决方案:

 grunt.registerTask('pluginsCp', function () {
    grunt.task.run(['pluginsCopy']);
  });