如何组合用户输入的字符串

时间:2018-04-04 18:19:09

标签: java android json recursion

我是java编程的新手。我的问题是我想将用户输入字符串从EditText拆分为2,3,4,5&组的组。 6。

例如,输入可能如下所示:"表中的闹钟嘈杂"

我想像这样分组。

按2 :(闹钟)(闹钟)(时钟输入)(在)(表格)(表格)(有噪音)

按3 :(闹钟)(闹钟输入)(时钟在)(表中)(表格)(表嘈杂)

按4 :(闹钟输入)(闹钟在)(表中的时钟)(在表中)(表是嘈杂的)

同样适用于5& 6.之后我将这些存储在一个数组中。

我只知道如何通过空格或其他分隔符拆分字符串。 到目前为止,这是我的代码:

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

但我不知道如何做到这一点。有人能帮助我吗?

1 个答案:

答案 0 :(得分: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);
}

您需要像getGroups这样的递归函数。您将在groups列表中找到结果。我检查了功能,发现它正常工作。

这是我用于测试的课程。您也可以使用以下类测试结果。

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