0

(标题可能具有误导性。我一直认为最困难的部分是找到合适的标题:D)

好吧,句子只是(长)字符串。我想以相反的方式显示这些句子。示例:"StackOverflow is a community of awesome programmers"将成为"programmers awesome of community a is StackOverflow".

所以我的想法是有一个分隔符,这里是一个空格。每当输入文本并按下空格键时,将该单词保存在一个列表中,一个 ArrayList,然后在 textView 中以倒序显示它们。

到目前为止,我只能输出文本但没有空格(programmersawesomeofcommunityaisStackOverflow)并且只能使用按钮。我使用下面的代码来做到这一点:

@Override
        public void onClick(View v) {
            String[] sentence = input.getText().toString().split(" "); //This split() method is the culprit!
            ArrayList<String> wordArray = new ArrayList<>();
            for (String word : sentence) {
                    wordArray.add(word);
            }
            Collections.sort(wordArray);
            StringBuilder invertedSentence = new StringBuilder();
            for (int i = wordArray.size(); i > 0; i--) {
                invertedSentence.append(wordArray.get(i - 1));
            }
            output.setText(invertedSentence.toString());
        }
    });

当系统检测到空格时,如何将句子(自动)保存在列表中作为拆分词?并在输出句子中添加空格?

谢谢你的时间。

4

1 回答 1

1

许多评论都有很好的建议,但这是您可以使用的一种方法:

    String[] sentence = new String("StackOverflow is a community of awesome programmers").split(" ");
    ArrayList<String> wordArray = new ArrayList<>();
    for (String word : sentence) {
       wordArray.add(0, word);
    }

    String backwards = String.join(" ", wordArray);
    System.out.println(backwards);

输出

programmers awesome of community a is StackOverflow
于 2018-08-15T17:22:10.857 回答