-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,082,665
  • 372
  • 3,610
  • 3,555
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
  • 11,561
  • 5
  • 45
  • 67
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,539
  • 12
  • 39
  • 70
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
Mengjun
  • 3,159
  • 1
  • 15
  • 21
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