标签:style blog http color os io strong art
参考代码:
1 // 10.cc 2 #include <iostream> 3 #include <cstring> 4 #include <string> 5 using namespace std; 6 7 void reverse(char* p_start, char* p_end) { 8 char t; 9 while(p_start < p_end) { 10 t = *p_start; 11 *p_start = *p_end; 12 *p_end = t; 13 14 p_start++; 15 p_end--; 16 } 17 } 18 19 char* reverse_str(char* str) { 20 if (NULL == str) 21 return NULL; 22 23 char* p_start = str; 24 char* p_end = str; 25 26 // 翻转每个单词 27 while(*p_start != ‘\0‘) { 28 if(*p_start == ‘ ‘) { 29 p_start++; 30 p_end++; 31 } else if (*p_end == ‘ ‘ || *p_end == ‘\0‘) { 32 reverse(p_start, --p_end); 33 p_start = ++p_end; 34 } else { 35 p_end++; 36 } 37 } 38 39 p_end = --p_start; 40 p_start = str; 41 // 整体翻转 42 reverse(p_start, p_end); 43 44 return str; 45 } 46 47 int main() { 48 cout << "input a string:" << endl; 49 string s; 50 getline(cin, s); 51 char *p = new char[s.size() + 1]; 52 strcpy(p, s.c_str()); 53 reverse_str(p); 54 cout << p << endl; 55 56 delete []p; 57 return 0; 58 }
转载自源代码
IT公司100题-10-翻转句子中单词的顺序,布布扣,bubuko.com
标签:style blog http color os io strong art
原文地址:http://www.cnblogs.com/dracohan/p/3899231.html