1. 程式人生 > >c++中字符串反轉的3種方法

c++中字符串反轉的3種方法

reverse ++ include char 編寫 div IT 字符 LG

第一種:使用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種方法