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


第一種:使用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;
}

第三種:使用string.h中的strrev函數

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char s[]="hello";

    strrev(s);

    cout<<s<<endl;

    return 0;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM