gpt4 book ai didi

java - 根据空格分割字符串

转载 作者:行者123 更新时间:2023-12-02 10:54:41 30 4
gpt4 key购买 nike

(标题可能会产生误导。我一直认为困难的部分是找到合适的标题:D)

嗯,句子只是(长)字符串。我想以相反的方式显示这些句子。示例:“StackOverflow 是一个很棒的程序员社区” 将变为 “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());
}
});

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

感谢您的宝贵时间。

最佳答案

许多评论都提出了很好的建议,但您可以使用以下一种方法:

    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

关于java - 根据空格分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51863285/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com