我有一个文本文件,其中包含以姓氏开头,然后是名字的名称,例如:
姓氏姓名
我需要输出它们从名字开始然后输出Surname.e.g 姓氏姓氏
我的代码以正确的顺序输出它们。我怎样才能以相反的方式使用它们?我的代码是:
public class SplitExample {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
FileInputStream fs3 = new FileInputStream("D:/Test.txt");
BufferedReader br3 = new BufferedReader(new InputStreamReader(fs3));
for(int c=0; c< 0; c++){
br3.readLine();
}
String name = br3.readLine().trim();
System.out.println(name);
}
}
答案 0 :(得分:1)
只需使用String#split,就像这样:
String[] arr = name.split(" ");`
String revName = String.format("%s %s", arr[1], arr[0]);
答案 1 :(得分:0)
这样做,我为了可读性而略显冗长
FileInputStream fileInputStream = new FileInputStream("C:/test.txt");
Scanner scanner = new Scanner(fileInputStream);
Scanner lineScanner;
String surname = "";
String name = "";
while (scanner.hasNextLine()) {
String delimiterInFile = " ";
String lineInFile = scanner.nextLine();
lineScanner = new Scanner(lineInFile).useDelimiter(delimiterInFile);
if(lineScanner.hasNext()){
surname = lineScanner.next();
}
if(lineScanner.hasNext()){
name = lineScanner.next();
}
System.out.println(String.format("%s %s", name, surname));
}