PAT 1009
import java.util.Scanner;
/*
题目:
每个测试用例的输出占一行,输出倒序后的句子。
输入样例:Hello World Here I Come
输出样例:Come I Here World Hello
思路:
先测取字符串长度n,从后往前遍历,找到' ',记录本轮' '位置a,
用字符串截取函数截取从本次空格位置到下次空格位置,打印输出
*/
public class PAT1009 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int k = str.length();
int a = k; //初始值为字符串末尾,后面作用为记录空格的位置
for(int j = k - 1; j >= 0; j--)
{
if(str.charAt(j) == ' ')
{
System.out.print(str.substring(j+1,a)+' ');
a = j;
}
//之前错误:首个字符不存在空格,所以无法输出首个单词,增加部分
if(j == 0)
{
System.out.print(str.substring(0,a));
}
}
}
}