Как получить подстроки в предложении, используя JAVA? - PullRequest
0 голосов
/ 08 января 2020

У меня есть строка "I read books", я хочу разделить это предложение на пробел и получить все подстроки, как показано ниже,

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

Как я могу получить этот вывод, используя java?

Ответы [ 3 ]

3 голосов
/ 08 января 2020

Попробуйте:

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

Вывод:

[I, I read, I read books, read, read books, books]
2 голосов
/ 08 января 2020

Попробуйте код ниже,

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);
}
1 голос
/ 08 января 2020
  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;
    }
  }
...