Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
思路:按照空格分割后存到字符串数组里,然后从后向前遍历存储,需要注意前面的空格和后面的空格。
注意区分“”和“ ”的区别。
package test;
public class str {
public static String reverseWords(String s) {
if (s == null) {
return "";
}
String[] array = s.split(" ");
StringBuilder res = new StringBuilder();
for (int i = array.length - 1; i >= 0; i--) {
if (!"".equals(array[i])) {
res.append(array[i]);
res.append(" ");
}
}
return res.length() == 0 ? "" : res.substring(0, res.length() - 1)
.toString();
}
public static void main(String[] args) {
System.out.print(reverseWords(" f ttt t "));
}
}