美文网首页
字符串相关

字符串相关

作者: 牵丝笼海 | 来源:发表于2018-07-01 16:46 被阅读10次

    记录一些与字符串相关的算法

    strcmp

    /*
    字符串比较函数
    s1 = s2: return 0;
    s1 > s2: return 1;
    s1 < s2: return -1;
     */
    int strcmp(const char* s1, const char* s2){
        if(NULL == s1 || NULL == s2)
            throw "Invalid arguments";
    
        int ret = 0;
        while(!(ret=*s1-*s2) && *s1 && *s2){
            ++s1;
            ++s2;
        }
        if(ret > 0){
            ret = 1;
        }else if(ret < 0){
            ret = -1
        }
    
        return ret;
    }
    

    strcpy

    /*
    把从s2地址开始且含有'\0'结束符的字符串复制到以s1开始的地址空间
     */
    char* strcpy(char* s1, const char* s2){
        if(NULL == s1 || NULL == s2)
            throw "Invalid arguments";
    
        char* p = s1;
        while((*s1++ = *s2++) != '\0');
    
        return p;
    }
    

    相关文章

      网友评论

          本文标题:字符串相关

          本文链接:https://www.haomeiwen.com/subject/uaxhuftx.html