1. 将句子中的单词逆序
eg.”hello world” ==> “world hello”
1 char* reverseStr(char* p_StrHead, char* p_StrEnd){ 2 if(p_StrHead == NULL || p_StrEnd == NULL)return NULL; 3 char ch = 0; 4 while(p_StrHead < p_StrEnd){ 5 ch = *p_StrHead; 6 *p_StrHead++ = *p_StrEnd; 7 *p_StrEnd-- = ch; 8 } 9 return p_StrHead; 10 } 11 12 char* reverseWord(char* str){ 13 if(str == NULL)return NULL; 14 15 size_t len = strlen(str); 16 reverseStr(str, str+len-1); 17 char* p_head = str; 18 char* p_end = str; 19 size_t i = 0; 20 21 while(i<len-1){ 22 if(*p_end == ' ' || *p_end == '\0'){ 23 reverseStr(p_head, p_end-1); 24 p_head = p_end+1; 25 } 26 p_end++; 27 i++; 28 } 29 return str; 30 } 31 32 33 34 int main(void/*int arg, char** agrv*/) 35 { 36 char srcStr[] = " x HTTP is my study "; // 37 cout << reverseWord(srcStr) << endl; 38 return 0; 39 }char* reverseStr(char* p_StrHead, char* p_StrEnd){ 40 if(p_StrHead == NULL || p_StrEnd == NULL)return NULL; 41 char ch = 0; 42 while(p_StrHead < p_StrEnd){ 43 ch = *p_StrHead; 44 *p_StrHead++ = *p_StrEnd; 45 *p_StrEnd-- = ch; 46 } 47 return p_StrHead; 48 } 49 50 char* reverseWord(char* str){ 51 if(str == NULL)return NULL; 52 53 size_t len = strlen(str); 54 reverseStr(str, str+len-1); 55 char* p_head = str; 56 char* p_end = str; 57 size_t i = 0; 58 59 while(i<len-1){ 60 if(*p_end == ' ' || *p_end == '\0'){ 61 reverseStr(p_head, p_end-1); 62 p_head = p_end+1; 63 } 64 p_end++; 65 i++; 66 } 67 return str; 68 } 69 70 71 72 int main(void/*int arg, char** agrv*/) 73 { 74 char srcStr[] = " x HTTP is my study "; // 75 cout << reverseWord(srcStr) << endl; 76 return 0; 77 }