实现字符串的语序翻转

来源:互联网 发布:windows 鼠标样式 编辑:程序博客网 时间:2024/05/29 14:24

如输入为“abc”
输出为"cba"

[cpp] view plaincopy
  1. //vs2005  
  2. #include "stdafx.h"  
  3. #include <iostream>  
  4. #include <string>  
  5. #include <stack>  
  6. using namespace std;  
  7.   
  8. void reverse(char *str)  
  9. {  
  10.     char *p,*q;  
  11.     string s1,s2;  
  12.     s1=str;  
  13.     p=str;  
  14.     q=str;  
  15.     int m=0,n=0;  
  16.     cout<<s1<<endl;  
  17.     stack<string> sstack;  
  18.     while(*q!='\0')  
  19.     {  
  20.         while(*q!=' ')//找到单词结束位置  
  21.             q++,n++;  
  22.         while(*q==' ')//找到单词开始位置  
  23.             q++,n++;          
  24.         s2=s1.substr(m,n-m);  
  25.         sstack.push(s2);  
  26.         p=q;  
  27.         m=n;  
  28.     }  
  29.     while(!sstack.empty())  
  30.     {  
  31.         cout<<sstack.top()<<' ';  
  32.         sstack.pop();  
  33.     }  
  34.     printf("\n");  
  35.   
  36.   
  37. }  
  38.   
  39. int _tmain(int argc, _TCHAR* argv[])  
  40. {  
  41.     char *str="i come from tianjin.";  
  42.     reverse(str);  
  43.     return 0;  
  44. }  
原创粉丝点击