【问题标题】:how to group string input by the user如何对用户输入的字符串进行分组
【发布时间】:2018-09-14 10:03:12
【问题描述】:

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

但我一点也不知道该怎么做。有人可以帮我吗?

【问题讨论】:

标签: java android json recursion


【解决方案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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多