自己实现strcpy与strncpy
Posted nanqiang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自己实现strcpy与strncpy相关的知识,希望对你有一定的参考价值。
#include <iostream> #include <string.h> using namespace std; char* Mystrcpy(char* dst,const char* src) { if(dst == NULL || src == NULL) return NULL; int i = 0; for(i = 0;src[i] != ‘‘;i++) { dst[i] = src[i]; } dst[i] = ‘‘; return dst; } char* Mystrncpy(char *dest, const char *src, size_t n) { if(dest == NULL || src == NULL) return NULL; int i; for (i = 0; i < n && src[i] != ‘‘; i++) dest[i] = src[i]; for ( ; i <= n; i++) dest[i] = ‘‘; return dest; } int main() { char dst[10]; char dst1[4]; char src[] = "hello"; Mystrcpy(dst,src); cout << dst << endl; Mystrncpy(dst1,src,3); cout << dst1 << endl; return 0;
//结果:
/*
hello
hel
*/
以上是关于自己实现strcpy与strncpy的主要内容,如果未能解决你的问题,请参考以下文章
[C/C++笔面试]不用库函数自己实现strcpy和strncpy