1. 程式人生 > >自己實現strcpy與strncpy

自己實現strcpy與strncpy

turn size_t stream rcp name ret ace color har

#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] != \0;i++)
    {
        dst[i] = src[i];
    }
    dst[i] = \0;
    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] != \0; i++) dest[i] = src[i]; for ( ; i <= n; i++) dest[i] = \0; 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