题目描述
反转单词顺序: 给定一个字符串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