1 #include <iostream> 2 #include <sstream> 3 using namespace std; 4 5 //通过首尾交换对字符串实现反转 6 char *revstr(char *str,size_t len) 7 { 8 char *start=str; 9 char *end=str+len-1; 10 char ch; 11 while (start<end) 12 { 13 ch=*start; 14 *start=*end; 15 *end=ch; 16 start++; 17 end--; 18 } 19 return str; 20 } 21 //计算并返回字符串长度 22 int Length(char *str) 23 { 24 int length=0; 25 while((*str++)!='\0') 26 length++; 27 return length; 28 } 29 30 //对单个单词字符反转 31 void _Reverse(char *str,int low,int high) 32 { 33 char tempChar; 34 while(low<high) 35 { 36 tempChar=str[low]; 37 str[low]=str[high]; 38 str[high]=tempChar; 39 low++; 40 high--; 41 } 42 } 43 44 //利用字符串流读取每个单词并将其反转,单词间有多个空格时合并为一个 45 void Reverse(char *str) 46 { 47 istringstream in(str); 48 int length; 49 for(string s;in>>s;) 50 { 51 length=Length(&s[0]); 52 _Reverse(&s[0],0,length-1); 53 cout<<s<<" "; 54 } 55 } 56 57 int main() // 要有main函数才行的 58 { 59 char test[] = "I love you"; 60 revstr(test, strlen(test)); 61 cout<<test<<endl; 62 Reverse(test); 63 }
结果显示: