思路:首先将整个句子按字符翻转,然后再将其中每个单词的字符旋转。
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 }
原文:http://www.cnblogs.com/sankexin/p/5636165.html