思路:首先將整個句子按字符翻轉,然後再將其中每個單詞的字符旋轉。
1 #include <string> 2 #include "stdafx.h" 3 4 void Reverse(char *pBegin, char *pEnd) 5 { 6 if(pBegin == NULL || pEnd == NULL) 7 return; 8 9 while(pBegin < pEnd) 10 { 11 char temp = *pBegin; 12 *pBegin = *pEnd; 13 *pEnd = temp; 14 15 pBegin ++, pEnd --; 16 } 17 } 18 19 char* ReverseSentence(char *pData) 20 { 21 if(pData == NULL) 22 return NULL; 23 24 char *pBegin = pData; 25 26 char *pEnd = pData; 27 while(*pEnd != '\0') 28 pEnd ++; 29 pEnd--; 30 31 // 翻轉整個句子 32 Reverse(pBegin, pEnd); 33 34 // 翻轉句子中的每個單詞 35 pBegin = pEnd = pData; 36 while(*pBegin != '\0') 37 { 38 if(*pBegin == ' ') 39 { 40 pBegin ++; 41 pEnd ++; 42 } 43 else if(*pEnd == ' ' || *pEnd == '\0') 44 { 45 Reverse(pBegin, --pEnd); 46 pBegin = ++pEnd; 47 } 48 else 49 { 50 pEnd ++; 51 } 52 } 53 54 return pData; 55 } 56 57 58 int main() 59 { 60 char input[] = "I am a student."; 61 printf("%s\n\n",input); 62 printf("After reverse.\n\n"); 63 ReverseSentence(input); 64 printf("%s\n", input); 65 66 return 0; 67 }