2016-10-26 1 views
-1

У меня есть строка, которая всегда меняется и похожа на случайное утверждение. То, что я хочу сделать, - это после 10 слов, которые я хочу разбить на строку, так что это две строки, когда я печатаю ее.java - Разделительная строка после слов x

Так, например:

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

Любая помощь в этом была бы большой, спасибо!

+0

@RayLloy Подстрока wil help in index, но для него его слова не являются символами –

+0

О да! вы правы, жаль, что я удаляю свой комментарий !! но [this] (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split (java.lang.String,% 20int)) можно использовать –

+1

Быстрое решение было бы использовать токенизатор или разделить на пробелы, чтобы получить отдельные слова, а затем построить их обратно в десятисловные строки. Но как @ShreyasSarvothama спрашивает, что вы пробовали и что пошло не так? – Buurman

ответ

0

Вот код: Код предполагает, что вы разделить максимум 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 
    } 

} 
+0

Wow спасибо большое! Я испытаю это сейчас, спасибо огромное :) – AliumCraft

+0

Почему бы не использовать 'String.split (" ")', чтобы найти количество слов? Я не вижу причин найти места так, как вы это делаете. – px06

+0

@ px06 кто сказал, что мы не можем это сделать? его просто другим способом. Но когда мы используем метод split (""), нам снова нужно найти индекс 10-го слова и повторить снова и снова. Лучше его закодируйте, чтобы вы увидели разницу. Здесь я просто просматриваю символ по характеру, так что мы имеем индексный счет, если мы используем метод split, нам снова нужно отследить индекс символов ... правильно? –

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

И в corrosponding JUnit-тест, который используют 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"); 
    } 
} 
+0

Это приятное решение. – px06

0

Другое решение:

import java.util.*; 
import java.lang.*; 
import java.io.*; 

class Ideone 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     System.out.println(
      Arrays.toString(
      splitSentence(
      "Random sentences can also spur creativity in other types of projects being done. If you are trying to come up with a new concept, a new idea or a new product, a random sentence may help you find unique qualities you may not have considered. Trying to incorporate the sentence into your project can help you look at it in different and unexpected ways than you would normally on your own." 
      ,10))); 
    } 

    public static String[] splitSentence(String sentence, int amount){ 
     String[] words = sentence.split(" "); 
     int arraySize = (int)Math.ceil((double)words.length/amount); 
     String[] output = new String[arraySize]; 
     int index=0; 
     int fullLines = (int)Math.floor((double)words.length/amount); 

     for(int i=0; i<fullLines; i++){ 
      String appender = ""; 
      for(int j=0; j<amount; j++){ 
       appender += words[index]+" "; 
       index++; 
      } 
      output[i] = appender; 
     } 
     String appender = ""; 
     for(int i=index; i<words.length; i++){ 
      appender += words[index]+" "; 
      index++; 
     } 
     output[fullLines] = appender; 
     return output; 
    } 

} 
Смежные вопросы