美文网首页
c++中字符串反转的3种方法

c++中字符串反转的3种方法

作者: Mjolnir1107 | 来源:发表于2017-10-17 11:01 被阅读0次

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

#include <iostream>  
#include <cstring>  
using namespace std;  
  
int main()  
{  
    char s[]="hello";  
  
    strrev(s);  
  
    cout<<s<<endl;  
  
    return 0;  
}  

第二种:使用algorithm中的reverse函数


#include <iostream>  
#include <string>  
#include <algorithm>  
using namespace std;  
  
int main()  
{  
    string s = "hello";  
  
    reverse(s.begin(),s.end());  
  
    cout<<s<<endl;  
  
    return 0;  
}  

第三种:自己编写

#include <iostream>  
using namespace std;  
  
void Reverse(char *s,int n){  
    for(int i=0,j=n-1;i<j;i++,j--){  
        char c=s[i];  
        s[i]=s[j];  
        s[j]=c;  
    }  
}  
  
int main()  
{  
    char s[]="hello";  
  
    Reverse(s,5);  
  
    cout<<s<<endl;  
  
    return 0;  
}  

相关文章

网友评论

      本文标题:c++中字符串反转的3种方法

      本文链接:https://www.haomeiwen.com/subject/cooruxtx.html