3

I am new in java programming. My problem is that I would like to split the user input string from an EditText to groups of 2,3,4,5 & 6.

For example, the input might look like: "the alarm clock in the table is noisy"

I would like to group them like this.

By 2: (the alarm) (alarm clock) (clock in) (in the) (the table) (table is) (is noisy)

By 3: (the alarm clock) (alarm clock in) (clock in the) (in the table) (the table is) (table is noisy)

By 4: (the alarm clock in) (alarm clock in the) (clock in the table) (in the table is) (the table is noisy)

Same goes to 5 & 6. Afterwards I store these in an array perhaps.

I only know how to split string through spaces or other delimiters. this is my code so far:

String[] text = editText.split(" ");
Log.d("Length", String.valueOf(text.length));
for (int i = 0; i < text.length; i++) {
    count = i;
    text[i] = text[i].trim();
    Log.d("Create Response", text[i]);
    params.add(new BasicNameValuePair("translate_me", text[i]));
}

But I don't have the slightest idea how to do this. Can someone help me?

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
blackblink
  • 33
  • 4

1 Answers1

1
String[] text = editText.getText().toString().split(" ");
List<String> wordList = new ArrayList<String>(Arrays.asList(text)); 

List<String> groups = new ArrayList<String>();
getGroups(3, wordList);

public static void getGroups(int n, List<String> wordList) {

    String temp = "";

    if (wordList.size() <= n) {
        for (String s : wordList)
            temp = temp + s + " ";
        groups.add(temp.trim());
        return;
    }

    for (int i = 0; i < n; i++)
        temp = temp + wordList.get(i) + " ";

    groups.add(temp);
    wordList.remove(0);
    getGroups(n, wordList);
}

You need a recursive function like getGroups. You will find the results in the groups list. I have checked the function and found it working.

Here's the class that I have used for testing. You can test the result as well using the following class.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {

    public static List<String> groups = new ArrayList<String>();
    public static String text = "the alarm clock in the table is noisy";

    public static void main(String[] args) {
        List<String> wordList = new ArrayList<String>(Arrays.asList(text.split(" ")));
        getGroups(3, wordList);

        System.out.println(groups);
    }

    public static void getGroups(int n, List<String> wordList) {

        String temp = "";

        if (wordList.size() <= n) {
            for (String s : wordList)
                temp = temp + s + " ";
            groups.add(temp.trim());
            return;
        }

        for (int i = 0; i < n; i++)
            temp = temp + wordList.get(i) + " ";

        groups.add(temp.trim());
        wordList.remove(0);
        getGroups(n, wordList);
    }
}
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98