strlen strcmp strcpy strcat的实现

时间:2022-12-30 16:11:27

size_t strlen(const char *str) 计算字符串str的长度,但不包括终止空字符

//尝试实现strlen 的功能 
int mystrlen(const char * s)
{
    int index = 0;
    while( s[index] != '\0' ){
        index++;
    }
    return index;
}
int main(int argc,char const *argv[])
{

    char s1[] = "abc";
    char s2[] = "123";
    printf("%d\n",strlen(s1));
    printf("%d\n",mystrlen(s1));
    return 0;
}

int strcmp(const char *str1, const char *str2) 比较字符串str1和字符串str2。
这个函数的返回值如下:

  • 如果返回值<0,则表明str1小于str2
  • 如果返回值,如果> 0,则表明str2 小于 str1
  • 如果返回值= 0,则表明str1 等于str2
//尝试实现 strcmp 的功能
//版本1 
int mystrcmp1(const char *s1, const char *s2)
{
    int index = 0;
    while( 1 ){
        if( s1[index] != s2[index] ){
            break;
        }else if( s1[index] == '\0' ){
            break;
        }
        index++;
    }   
    return s1[index] - s2[index];
} 

//版本二
int mystrcmp2(const char *s1, const char *s2)
{
    int index = 0;
    while( s1[index] == s2[index] && s1[index] != '\0'  ){
        index++;
    }   
    return s1[index] - s2[index];
} 

//版本三
int mystrcmp(const char *s1, const char *s2)
{
    while( *s1 == *s2 && *s1 != '\0' ){
        s1++;
        s2++; 
    }
    return *s1 - *s2; 
}
int main(int argc,char const *argv[])
{

    char s1[] = "abc";
    char s2[] = "abb";
    printf("%d\n",strcmp(s1,s2));
    printf("%d\n",mystrcmp(s1,s2));
    return 0;
}

char *strcpy(char *restrict dst, const char *restrict src) 复制src指向的字符串到dst

//尝试实现 strcpy 的功能
//版本1 
char *mystrcpy1(char* dst,const char* src)
{
    int index = 0;
    while( src[index] != '\0' ){
        dst[index] = src[index];
        index++;
    }
    dst[index] = '\0';
    return dst;
}

//版本2
char *mystrcpy2(char* dst,const char* src)
{
    char* ret = dst;
    while( *src != '\0' ){
        *dst = *src;
        dst++;
        src++;
    }
    *dst = '\0';
    return ret;
} 
//版本3
char *mystrcpy3(char* dst,const char* src)
{
    char* ret = dst;
    while( *src  ){
        *dst++ = *src++;
    }
    *dst = '\0';
    return ret;
} 
//版本4
char *mystrcpy(char* dst,const char* src)
{
    char* ret = dst;
    while( *dst++ = *src++  )
        ;
    *dst = '\0';
    return ret;
} 
int main(int argc,char const *argv[])
{

    char s1[] = "abc";
    char s2[] = "abb";
    printf("before s1:%s\n",s1);
    printf("after s1:%s\n",mystrcpy(s1,s2));
    return 0;
}

char *strcat(char *dest, const char *src) 连接两个字符串,写入到dest中

//尝试实现 strcat
char *mystrcat(char *s1, const char *s2)
{
    while(*s1 != '\0'){
        *s1++;
    }
    while(*s2 != '\0'){
        *s1++=*s2++;
    }
    *s1='\0'; 
    return s1;
}
int main()
{
    char s1[]="hello";
    char s2[]="world!";
    mystrcat(s1,s2);
    printf("%s\n",s1);
    return 0;
}

自己动手写的函数,虽然稍有不同,但现代的哦编译器基本会编译成几乎相同的代码,执行效率并无太大的区别