用C语言的指针改写strlen、strcpy、strcmp、strcat

第一题:改写strlen

代码

#include <stdio.h>  
#include <string.h>  
  
int main(int argc, const char *argv[]) {  
    char str[128] = "";  
    printf("sizeof: %ld
", sizeof(str));  
    printf("请输入字符串
");  
    scanf("%s", str);  
    printf("strlen: %ld
", strlen(str));  
    int count = 0;  
    char *p = str;  
    while (*p != '') {  
        count++;  
        p++;  
    }  
    printf("count=%d
", count);  
    return 0;  
}

第二题:改写strcpy

代码

#include <stdio.h>  
#include <string.h>  
  
int main(int argc, const char *argv[]) {  
    int a = 10;  
    int b = a;  
    char str1[128] = "hello";  
    char str2[10];  
    char *p1, *p2;  
  
    p1 = str1;   
    p2 = str2;   
    while (*p1 != '') {  
        *p2 = *p1;   
        p1++;   
        p2++;   
    }  
    *p2 = '';   
    return 0;
}

第三题:改写strcmp

代码

#include <stdio.h>  
  
int main() {  
    char str1[32] = "hello";  
    char str2[10] = "hello9";  
    char *p1 = str1, *p2 = str2;  
    int res;  
  
    while (*p1 != '' || *p2 != '') 
    {  
        res = *p1 - *p2;  
        if (res != 0) 
    {  
            break;  
        }  
        p1++;  
        p2++;  
    }  
  
    printf("res=%d
", res);  
    return 0;  
}

第四题:改写strcat

代码

#include <stdio.h>  
  
int main(int argc, const char *argv[])
{  
    char str1[128] = "abcdef";  
    char str2[] = "1234";  
    char *p1 = str1;  
  
    while (*p1 != '') {  
        p1++;  
    }  
    const char *p2 = str2;  
    while (*p2 != '') {  
        *p1 = *p2;  
        p1++;  
        p2++;  
    }  
    *p1 = '';
    printf("Result: %s
", str1); 
    return 0;  
}