分享

c++笔试基础 之 06 字符串反转的方法

 雪柳花明 2017-02-16

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

  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函数

  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. }

第三种:自己编写

  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. }  

第四种:

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. string resverstr(const string str)
  5. {
  6. string temp;
  7. int len = str.length();
  8. cout << "字符串长度"<<len << endl;
  9. for (int i = 0; i < len; i++)
  10. {
  11. temp = str[i] + temp;
  12. }
  13. return temp;

  14. }



第五种:
  1.  
  2. string resverstr5(string str)
  3. {
  4. int len = str.length();
  5. cout << "字符串长度" << len << endl;
  6. for (int i = 0; i < len/2; i++)
  7. {
  8. char c = str[i];
  9. str[i] = str[str.length() - i - 1];
  10. str[str.length() - i - 1] = c;
  11. }
  12. return str;
  13. }





    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多