[ C語言生活記事 ] - String 相關的 function (1) strcpy

簡單實現C語言中有幾個string相關的function。

part 1 - strcpy  (string copy)

 

Function Name : strcpy

Definition : Copies the C string pointed by source into the array pointed by destination, including the terminating null character and stopping at that point.

Prototype : char *strcpy ( char *destination, const char *source );

 

#include <stdio.h>

char *strcpy_imp ( char *dest , const char *src )
{
    if((dest == NULL) || (src == NULL))
    {
        printf("[%d %s] Input string is invalid.\n",__LINE__,__FUNCTION__);
        return NULL;
    }

    char *ret_ptr = dest;
    while(( *dest++ = *src++ ) != '\0');
    return ret_ptr;
}

int main()
{
    char s1[30] = "string1";
    char *s2 = "abc";
    
    printf("result = %s\n",strcpy_imp(s1,s2));

    return 0;
}


Result :

sh-4.2$ gcc -o main *.c
sh-4.2$ main
result = abc