模拟实现不受限制的字符串函数(strcat、strcpy、strcmp)

来源:互联网 发布:关于清朝的纪录片 知乎 编辑:程序博客网 时间:2024/06/05 13:51

使用这些函数时,需要注意到以下几点:
1)目标空间足够大,
2)原字符串有‘\0
目标空间可改 (strcpy 字符串拷贝)
目标字符串中’\0’被覆盖(strcat 字符串追加)
目标空间不可改(strcmp 字符串比较)
3)断言(assert)

三个库函数的原型为下:

char *strcpy( char *strDestination, const char *strSource );char *strcat( char *strDestination, const char *strSource );int strcmp( const char *string1, const char *string2 );

//模拟实现strcpy(字符串拷贝)

char*my_strcpy(char* pdest, const char*psrc){    char *ret = pdest;    assert(pdest);    assert(psrc);    while (*psrc != NULL)    {        *pdest = *psrc;        pdest++;        psrc++;    }    return ret;}int main(){    int *arr = "abcdef";    int buf[20] = { 0 };    my_strcpy(buf, arr);    printf("%s\n", buf);    system("pause");    return 0;}

//模拟实现strcmp(字符串比较)

int my_strcmp(const char *string1, const char *string2){    assert(string1 != NULL);    assert(string2 != NULL);    while (*string1 == *string2)    {        if (*string1 == '\0')            return 0;        string1++;//如果相等,则一直向后比较        string2++;    }    return *string1 - *string2;//如果两者不相等,则利用ascll值返回}int main(){    char *arr1 = "abcde";    char *arr2 = "abcd";    int ret = my_strcmp(arr1, arr2);    printf("%d\n", ret);    system("pause");    return 0;}

//strcat字符串追加

char *strcat( char *strDestination, const char *strSource );char *my_strcat(char *pdest, const char *pstr){    assert(pdest!= NULL);    assert(pstr != NULL);    char *ret = pdest;    while (*pdest != '\0')//找目标空间的'\0'    {        pdest++;    }    while (*pstr != '\0')//拷贝字符串到目标空间    {        *pdest = *pstr;        *pdest++;        *pstr++;    }    return ret;}int main(){    char arr[20] = "hello ";    char*p = "world";    my_strcat(arr, p);    printf("%s\n", arr);    system("pause");    return 0;}

学习这些字符串比较函数,对我们今后学习字符串有很大的帮助,希望这些可以帮助到大家。

阅读全文
0 0
原创粉丝点击