C語言反轉字符串


1.使用string.h中的strrev函數

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

 

2.使用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;  
}  

  

3.自己編寫

#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;  
}  

  

或者

char *revstr(char *str, size_t len)
{

    char    *start = str;
    char    *end = str + len - 1;
    char    ch;

    if (str != NULL)
    {
        while (start < end)
        {
            ch = *start;
            *start++ = *end;
            *end-- = ch;
        }
    }
    return str;
}

  

C語言中所謂的字符串不過是字符數組,后跟一個0x00字符標識結尾,所以反轉起來很容易,只要一個循環依次將第一個字符和最后一個字符交換,第二個字符和倒數第二個字符交換……如果最中間有兩個字符(即需要反轉的字符串長度為偶數),那就交換,如果最中間有一個字符(即需要反轉的字符串長度為奇數),那就不需要碰它。還有就是最后一個用來標識字符串結尾的0x00字符不用動它。


免責聲明!

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



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