strcpy
char *strcpy(char *dest, const char *src) 把 src 所指向的字符串复制到 dest。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>char* my_strcpy(char *dst, char *src)
{if(dst == NULL || src == NULL){return NULL;}char *ret = dst;while((*dst++ = *src++) != '\0');return ret;
}int main()
{char src[10];scanf("%s", &src);char *dst = malloc(sizeof(src));dst = my_strcpy(dst, src);printf("%s", dst);
}
mempcy
- 增加内存重叠检测,避免dst与src重叠时(即dst>=src && dst <= src+strlen(src)),src的尾'\0'被覆盖,报错。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>char* my_memcpy(char *dst, const char* src, int num)
{if(dst == NULL || src == NULL) return NULL;char *ret = dst;// dst 与 src 内存重叠 : 从高地址开始复制if(dst >= src && dst <= src + num){dst = dst + num - 1;src = src + num - 1;while(num--){*dst-- = *src--;}}// dst 与 src 无内存重叠 : 从地址开始复制else{while(num--){*dst++ = *src++; }}return ret;
}char* my_strcpy(char *dst, const char *src)
{if(dst == NULL || src == NULL){return NULL;}return my_memcpy(dst, src, strlen(src)+1);
}int main()
{char src[3];scanf("%s", &src);my_strcpy(src+1, src);printf("%s", src);
}
- void *memcpy(void *str1, const void *str2, size_t n) 从存储区 str2 复制 n 个字节到存储区 str1。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>void* my_memcpy(void *dst, const void* src, size_t num)
{if(dst == NULL || src == NULL) return NULL;void *ret = dst;// dst 与 src 内存重叠 : 从高地址开始复制if(dst > src && (char*)dst < (char*)src + num){dst = (char*)dst + num - 1;src = (char*)src + num - 1;while(num--){*(char*)dst-- = *(char*)src--;}}// dst 与 src 无内存重叠 : 从地址开始复制else{dst = (char*)dst;src = (char*)src;while(num--){*(char*)dst++ = *(char*)src++; }}return ret;
}char* my_strcpy(char *dst, const char *src)
{if(dst == NULL || src == NULL){return NULL;}return my_memcpy(dst, src, strlen(src)+1);
}int main()
{/*char src[3];scanf("%s", &src);my_strcpy(src+1, src);printf("%s", src);*/int src[3];for(int i=0; i<3; i++){scanf("%d", &src[i]); }my_memcpy(src+1, src, sizeof(int)*2);for(int i=0; i<3; i++){printf("%d ", src[i]);}}
strcat
char *strcat(char *dest, const char *src) 把 src 所指的字符串追加到 dest 所指向的字符串的结尾
#include <stdio.h>
#include <stdlib.h>
#include <string.h>char* strcat(char* dst, const char* src)
{if(dst == NULL || src == NULL) return NULL;//char *ret = dst;while(*dst != '\0'){dst++;}while((*dst++ = *src++) != '\0');return ret;
}int main()
{char src[3];fgets(src, 3, stdin);//scanf("%s",&src);char dst[12] = "capybara_";printf("%s", strcat(dst, src));
}