第一题:改写strlen
代码
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[]) {
char str[128] = "";
printf("sizeof: %ld\n", sizeof(str));
printf("请输入字符串\n");
scanf("%s", str);
printf("strlen: %ld\n", strlen(str));
int count = 0;
char *p = str;
while (*p != '\0') {
count++;
p++;
}
printf("count=%d\n", 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 != '\0') {
*p2 = *p1;
p1++;
p2++;
}
*p2 = '\0';
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 != '\0' || *p2 != '\0')
{
res = *p1 - *p2;
if (res != 0)
{
break;
}
p1++;
p2++;
}
printf("res=%d\n", 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 != '\0') {
p1++;
}
const char *p2 = str2;
while (*p2 != '\0') {
*p1 = *p2;
p1++;
p2++;
}
*p1 = '\0';
printf("Result: %s\n", str1);
return 0;
}