热门

最新

红包

立Flag

投票

同城

我的

发布
weixin_51959559
weixin_51959559
4 年前
trueweixin_51959559

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));
}
}
}

}

CSDN App 扫码分享
分享
2
点赞
打赏
  • 复制链接
  • 举报
下一条:
好久没有写过博客了这几个月一直都在做新的项目,过段时间整理好再分享下吧
立即登录