200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 算法-给定一个字符串S = “I am a student. “ 则输出“student. a am I“。

算法-给定一个字符串S = “I am a student. “ 则输出“student. a am I“。

时间:2019-01-14 07:22:19

相关推荐

算法-给定一个字符串S = “I am a student. “ 则输出“student. a am I“。

题目描述

反转单词顺序: 给定一个字符串S = "I am a student. “,则输出"student. a am I”。

算法实现

public static void main(String[] args) {String str = "I am a student. ";String result = reverseWords(str);System.out.println(result);}public static String reverseWords(String str) {String space = " ";String[] s = str.trim().split(space);StringBuilder sb = new StringBuilder();for (int i = s.length - 1; i >= 0; i--) {String s1 = s[i];// 对于单词间存在连续空格情况处理, eg. "I am astudent."if ("".equals(s1)) {continue;}sb.append(s1).append(space);}// 去掉最后多余的空格return sb.toString().trim();}

运行结果

student. a am I

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。