句子反转

题目:

给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割,

单词之间只有一个空格,前后没有空格。 比如: (1) “hello xiao mi”-> “mi xiao hello”

分析:此题目的重点在于对输出末尾空格的控制。

 1 package test01;
 2 
 3 import java.util.Scanner;
 4 
 5 public class FanZhuan01 {
 6 
 7     public static void main(String[] args) {
 8         Scanner scan = new Scanner(System.in);
 9         while(true){                //此处使用true是为了能够输入多组数据,每组数据占据一行
10             String str = scan.nextLine();
11             String[] st = str.split(" ");
12             for(int i=st.length-1;i>=0;i--){
13                 if(i == 0){
14                     System.out.print(st[i]);
15                 }else{
16                     System.out.print(st[i] + " ");
17                 }
18             }
19             System.out.println();
20         }
21     }
22 }
原文地址:https://www.cnblogs.com/XuGuobao/p/7366002.html