字符串反转方法总结

来源:互联网 发布:淘宝用的最多的快递 编辑:程序博客网 时间:2024/06/05 12:45

第一种:使用string.h中的strrev函数

[cpp] view plain copy
  1. #include <iostream>  
  2. #include <cstring>  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     char s[]="hello";  
  8.   
  9.     strrev(s);  
  10.   
  11.     cout<<s<<endl;  
  12.   
  13.     return 0;  
  14. }  
第二种:使用algorithm中的reverse函数

[cpp] view plain copy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <algorithm>  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     string s = "hello";  
  9.   
  10.     reverse(s.begin(),s.end());  
  11.   
  12.     cout<<s<<endl;  
  13.   
  14.     return 0;  
  15. }  

第三种:自己编写

[cpp] view plain copy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. void Reverse(char *s,int n){  
  5.     for(int i=0,j=n-1;i<j;i++,j--){  
  6.         char c=s[i];  
  7.         s[i]=s[j];  
  8.         s[j]=c;  
  9.     }  
  10. }  
  11.   
  12. int main()  
  13. {  
  14.     char s[]="hello";  
  15.   
  16.     Reverse(s,5);  
  17.   
  18.     cout<<s<<endl;  
  19.   
  20.     return 0;  
  21. }  
原创粉丝点击