zoukankan      html  css  js  c++  java
  • 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字符不用动它。

  • 相关阅读:
    redis基础配置
    brew安装mysql
    iptables 执行清除命令 iptables -F 要非常小心
    nginx反向代理部署nodejs配置
    Starting MySQL... ERROR! The server quit without updating PID file 问题解决
    iframe自适应高度问题
    js正则常用的一些东西
    node.js批量重命名文件
    [转]MySQL5字符集支持及编码研究
    PHP $_SERVER的使用
  • 原文地址:https://www.cnblogs.com/shenckicc/p/7045660.html
Copyright © 2011-2022 走看看