给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: "the sky is blue".
输出: "blue is sky the".
说明:
- 无空格字符构成一个单词。
- 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
- 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
题目分析:
将字符串里面的单词翻转,并去除多余的空格;可以使用split()函数将字符串中的字符按空格“ ”分隔,然后从字符串的尾部开始将一个个单词加入新字符串中,并在每个单词之间加入空格。
代码实现:
public String reverseWords(String s) { if (s == null || s.length() == 0) return ""; String[] string = s.split(" "); String res = ""; for (int i = string.length - 1; i >= 0; i--) { if (!string[i].equals("")){ if (res.length() > 0){ res += " "; } res += string[i]; } } return res; }
主函数:
public static void main(String[] args) { S2 s = new S2(); String string = "the sky is blue"; String res = s.reverseWords(string); System.out.println(res); }
运行结果:
blue is sky the