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字符不用动它。

posted @ 2017-06-18 22:20  悟空的爸爸  阅读(10758)  评论(0编辑  收藏  举报