代码之家  ›  专栏  ›  技术社区  ›  esQmo_

基于空格拆分字符串

  •  0
  • esQmo_  · 技术社区  · 6 年前

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

    所以我的想法是用一个分隔符,这里是 空白处

    到目前为止,我只能输出文本,但没有空格( 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());
            }
        });
    

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Bill    6 年前

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

        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