我正在尝试从文件中反转单词和行,但我的代码只会在不保留每个句子的格式并打印新行的情况下反转单词。
这是文件的示例以及输出的外观。
reverse.txt(实际):
He looked for a book.
He picked up the book.
He read the book.
He liked the book.
预期结果:
book. the liked He
book. the read He
book. the up picked He
book. a for looked He
这是我到目前为止的JAVA代码
import java.io.*;
import java.util.*;
public class ReverseOrder {
public static void main (String[] args)
throws FileNotFoundException {
ArrayList<String> revFile = new ArrayList<String>();
Scanner input = new Scanner(new File("reverse.txt"));
while (input.hasNext()){
revFile.add(input.next());
for(int i = revFile.size()-1; i >= 0; i--){
System.out.println(revFile.get(i) + " ");
}
}
}
}
答案 0 :(得分:3)
你可以试试这个: -
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReverseOrder {
/**
* @param args
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
ArrayList<String> revFile = new ArrayList<String>();
Scanner input = new Scanner(new File("/reverse.txt"));
while (input.hasNextLine()){
revFile.add(input.nextLine());
}
for(int i = (revFile.size()-1); i >=0 ; i--){
String ar[]=revFile.get(i).split(" ");
for(int j = (ar.length-1); j >=0; j--){
System.out.print(ar[j] + " ");
}
System.out.println(" ");
ar=null;
}
}
}
输出: -
book. the liked He
book. the read He
book. the up picked He
book. a for looked He
希望它会对你有所帮助。
答案 1 :(得分:1)
我的Yoda式建议
public static void main(String[] args) {
String s = "I want cake today.";
String[] ss = s.split(" ");
Stack<String> sss = new Stack<>();
for(String ssss:ss){
sss.push(ssss);
}
while(!sss.isEmpty()){
System.out.print(sss.pop());
System.out.print(" ");
}
}
给出
today. cake want I
对于行,对另一个堆栈执行相同操作。
或者,如果您不想使用Stacks,请将令牌和行存储到某个ArrayList中并使用Collections.reverse(list)
答案 2 :(得分:0)
您可以使用
org.apache.commons.lang.StringUtils;
它具有与String相关的各种方法。为了您的目的,您可以使用: StringUtils.reverseDelimited(str,'')函数如下:
while (input.hasNext()) {
String str = input.nextLine();
System.out.println(str);
System.out.println(StringUtils.reverseDelimited(str, ' '));// <- reverse line
}