实现以下函数 char *my_strcpy(char *dest,char const *src); char *my_strncpy(char *dest,char const *src,int len); char *my_strcat(char *dest,char const *src); char *my_strncat(char *dest,char const *src,int len); int my_strcmp(char *str1,char const *str2); int my_strncmp(char *srr1,char const *str2,int len);
时间: 2023-07-23 20:08:28 浏览: 144
下面是实现上述函数的示例代码:
```c
#include <stdio.h>
char *my_strcpy(char *dest, char const *src) {
char *temp = dest;
while ((*dest++ = *src++))
;
return temp;
}
char *my_strncpy(char *dest, char const *src, int len) {
char *temp = dest;
while (len > 0 && (*dest++ = *src++)) {
len--;
}
if (len > 0) {
*dest = '\0';
}
return temp;
}
char *my_strcat(char *dest, char const *src) {
char *temp = dest;
while (*dest) {
dest++;
}
while ((*dest++ = *src++))
;
return temp;
}
char *my_strncat(char *dest, char const *src, int len) {
char *temp = dest;
while (*dest) {
dest++;
}
while (len > 0 && (*dest++ = *src++)) {
len--;
}
if (len > 0) {
*dest = '\0';
}
return temp;
}
int my_strcmp(char *str1, char const *str2) {
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
return *(unsigned char *)str1 - *(unsigned char *)str2;
}
int my_strncmp(char *str1, char const *str2, int len) {
while (len > 0 && *str1 && (*str1 == *str2)) {
str1++;
str2++;
len--;
}
if (len == 0) {
return 0;
}
return *(unsigned char *)str1 - *(unsigned char *)str2;
}
int main() {
char dest[100] = "Hello";
char src[] = "World";
printf("strcpy: %s\n", my_strcpy(dest, src));
char dest2[100] = "Hello";
printf("strncpy: %s\n", my_strncpy(dest2, src, 3));
char dest3[100] = "Hello";
printf("strcat: %s\n", my_strcat(dest3, src));
char dest4[100] = "Hello";
printf("strncat: %s\n", my_strncat(dest4, src, 3));
char str1[] = "abc";
char str2[] = "abc";
printf("strcmp: %d\n", my_strcmp(str1, str2));
char str3[] = "abcd";
char str4[] = "abce";
printf("strncmp: %d\n", my_strncmp(str3, str4, 3));
return 0;
}
```
上述代码演示了如何实现 `my_strcpy`、 `my_strncpy`、 `my_strcat`、 `my_strncat`、 `my_strcmp` 和 `my_strncmp` 函数。你可以根据需要调用这些函数,并根据具体的参数和返回值进行相应的操作。
阅读全文