【问题标题】:Split Strings based on white spaces基于空格分割字符串
【发布时间】:2018-08-15 17:07:48
【问题描述】:

(标题可能具有误导性。我一直认为最困难的部分是找到合适的标题: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());
        }
    });

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

感谢您的宝贵时间。

【问题讨论】:

  • 你为什么要对wordArray进行排序?空格的 regex\\s.
  • "" 是一个 _empty 字符串。它甚至不包含空格。我假设您的意思是" ""\\s+"(任何空格,包括制表符等)。此外,您可能希望在组装倒置句子时添加一些空格,例如通过invertedSentence.append(" ").append(wordArray.get(i - 1)); 或更好地使用Java 8 的流来反转数组并使用join(" ") 连接字符串。
  • 附带说明:Collections.sort(wordArray); 反转列表但对其进行排序,即您的示例文本将变为 a awesome community is of programmers StackOverflow(假设其余部分是正确的) .
  • @Thomas 谢谢。我试图找到一种在倒置句子中添加空格的方法
  • @ElliottFrisch 这样我就可以向后循环输出倒置的句子。我错了

标签: java android regex textutils


【解决方案1】:

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

    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

【讨论】:

  • String.join 需要 Android O
  • @esQmo_,您发布的代码似乎拆分为一个空字符串。
  • 这是一个错字,因为我没有复制粘贴它。我要解决这个问题
  • 如何让这段代码在安卓设备版本上运行
  • 这个答案,可能会有所帮助:stackoverflow.com/questions/33802971/… 它建议使用TextUtils.join
猜你喜欢
  • 2013-10-11
  • 2012-09-22
  • 1970-01-01
  • 2014-12-13
  • 2013-08-02
  • 2023-04-02
  • 1970-01-01
  • 2021-09-23
  • 2012-04-22
相关资源
最近更新 更多