-1

I have a string "I read books", I want to split this sentence by space and get all the sub strings like below,

"I",
"I read",
"I read books",
"read",
"read books",
"books"

How can i get this output using java?

Hülya
  • 3,353
  • 2
  • 12
  • 19
Sachin Muthumala
  • 775
  • 1
  • 9
  • 17

3 Answers3

3

Try this:

String s = "I read books";
String[] arr = s.split("\\s");
List<String> list = new ArrayList<>();
for(int i=0; i<arr.length; i++) {
    int t = i;
    String temp = "";
    while(t<arr.length) {
        list.add(temp + arr[t]);
        temp += arr[t] + " ";
        t++;
    }
}
System.out.println(list);

Output:

[I, I read, I read books, read, read books, books]
Hülya
  • 3,353
  • 2
  • 12
  • 19
2

Try below code,

String str = "I read books";
String[] allWords = str.split(" ");
List<String> combinations = new ArrayList<>();
String wordStart;
for(int i=0; i<allWords.length; i++) {
    wordStart = allWords[i];
    combinations.add(wordStart);
    for(int j=i+1; j<allWords.length; j++) {
        wordStart = wordStart + " " + allWords[j];
        combinations.add(wordStart);
    }
}
for (String combination: combinations) {
    System.out.println(combination);
}
Vivek
  • 376
  • 1
  • 14
1
  public class JavaFiddle
  {
        public static void main(String[] args)
    {

      String str= "I read books";
      java.util.ArrayList<Integer> indexList =  getIndexList(str," ");
      //System.out.println(indexList.size());
      for (int counter = 0; counter < indexList.size()-1; counter++) {  
           for (int innerCounter = counter; innerCounter < indexList.size(); innerCounter++) {
                //System.out.println(indexList.get(counter)+ " " + indexList.get(innerCounter)  ); 
                System.out.println( str.substring(indexList.get(counter),indexList.get(innerCounter)));
          }
      }   
    }


    public static java.util.ArrayList<Integer> getIndexList (String text, String separator )
    {  
        java.util.ArrayList<Integer> indexList = new java.util.ArrayList<Integer>();
        indexList.add(0);
         for (int index = text.indexOf(separator);
                 index >= 0;
                 index = text.indexOf(separator, index + 1))
         {
            //System.out.println(index);
            indexList.add(index);
        }
        indexList.add(text.length()-1);
        return indexList;
    }
  }
divyang4481
  • 1,584
  • 16
  • 32