-8

Is there a way to take the following sentence:

"I want this split up into pairs"

and generate the following list using java:

"I want", "want this", "this split", "split up", "up into", "into pairs"

BalusC
  • 1,040,783
  • 362
  • 3,548
  • 3,513
sabra2121
  • 61
  • 9

4 Answers4

2

There is a way, lots of ways one of these can be:

String string = "I want this split up into pairs";
String[] words = string.split(" ");
List<String> pairs = new ArrayList<String>();
for (int i = 0; i < words.length-1; ++i) {
    pairs.add(words[i] + " " + words[i+1]);
}
System.out.println(pairs);
Maciej Dobrowolski
  • 10,778
  • 3
  • 45
  • 65
0

This is a basic algo

Tokenize or split your sentence

 I want this split up into pairs -> I, want, this, split, up, into, pairs

Then

first = read first word
while(there are more words to read){
    second = read next word
    Print first + " " + second
    first = second
}
Ankit Rustagi
  • 5,391
  • 11
  • 37
  • 68
0

An example is as follows:

    String text = "I want this split up into pairs";
    String[] words = text.split(" ");

    //Print 2 combined words
    for(int i=1;i<words.length;i++)
    {
        System.out.printf("%s %s\n", words[i-1],words[i]);
    }

Output in Console:

I want
want this
this split
split up
up into
into pairs
MouseLearnJava
  • 3,101
  • 1
  • 13
  • 20
0

Not a huge java person, so not sure if this code is 100% but it's a general idea for one option.

    String x = "I want this split up into pairs";
    String[] parts = x.split(" ");
    List<String> newParts = new ArrayList<String>();;
    for (int i = 0; i < parts.length()-1; i++) {
        newParts.add(parts[i]+parts[i+1]);
    }

Then, the newParts List will have all your pairs

Alex Chumbley
  • 3,062
  • 7
  • 31
  • 58