翻转单词顺序
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,为简单起见,标点符号和普通字母一样处理
示例
输入:I am a student.
输出:student. a am I
思路:按照空格分割字符串,交换字符串
public class ReverseWordsInSentence {
private String reverse(String str) {
String[] strs = str.split(" ");
int start = 0;
int end = strs.length - 1;
while (start < end) {
String t = strs[start];
strs[start] = strs[end];
strs[end] = t;
start++;
end--;
}
StringBuffer sb = new StringBuffer();
for (String s : strs) {
sb.append(s).append(" ");
}
return sb.toString().trim();
}
}
网友评论