gpt4 book ai didi

java - 颠倒每个句子

转载 作者:行者123 更新时间:2023-12-01 18:57:17 25 4
gpt4 key购买 nike

假设我的输入是

now is the time for
all good men to come to the aid of the party

输出将是:

for time the is now
party the of aid the to come to men good all

我想出了如何反转整个文本文件,但我需要逐句执行。目前我的代码输出如下:

party the of aid the to come to men good all for time the is now

代码是:

List<String> words = new ArrayList<String>();

while(sc.hasNextLine())
{
String line = sc.nextLine();
StringTokenizer st = new StringTokenizer(line);
while(st.hasMoreTokens())
{
words.add(st.nextToken());
}
}
for (int i = 0; i <words.size(); i++)
{
System.out.print(words.get(words.size()-i-1) + " ");
}

最佳答案

如果使用 split() 会更简单String 类的用于分割行的方法,它是按空格分割的首选方法(而不是使用 StringTokenizer,后者在所有实际用途中都被视为 deprecated)。此外,每行结束后的换行符也会出现问题 - 事实上,您应该使用列表列表,其中每个列表保存单行的单词。试试这个:

List<List<String>> words = new ArrayList<List<String>>();

while (sc.hasNextLine()) {
String line = sc.nextLine();
words.add(Arrays.asList(line.split("\\s+")));
}

for (List<String> list : words) {
for (int i = list.size()-1; i >= 0; i--)
System.out.print(list.get(i) + " ");
System.out.println();
}

关于java - 颠倒每个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13521810/

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