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?
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?
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]
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);
}
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;
}
}