如将字符串 "i am a student."翻转后的结果应该为"student. a am i"
思路:先翻转整个句子,再翻转句子中的单词
两次翻转达到结果(i am a student.)-(.tneduts a ma i)- (student. a am i)
// 思路:先翻转整个句子,再翻转句子中的单词 // 两次翻转达到结果(i am a student.)-(.tneduts a ma i)- // (students a am i) public static void main(String[] args) { String word = "i am a student."; System.out.println("原始字符串:"+word); // 1、翻转整个句子 String resultWord=reverse(word.toCharArray()); System.out.println("翻转整个句子后字符串:"+resultWord); // 2、翻转句子中的每个单词 String[] array=resultWord.split(" "); System.out.println("翻转句子中每个单词后的字符串:"); for (int i = 0; i < array.length; i++) { array[i]=reverse(array[i].toCharArray()); System.out.print(array[i]+" "); } } /* * 翻转句子 */ private static String reverse(char[] word) { if (word == null || "".equals(word)) { return null; } else { int start = 0; int end = word.length - 1; int middle = (start + end) / 2; char temp = ' '; while (start <=middle && end >= middle) { temp = word[start]; word[start] = word[end]; word[end] = temp; start++; end--; } } return new String(word); }