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

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

part 4 - strcat (string concatenate)

Function Name : strcat

Definition : Appends a copy of the source string to the destination string.
    The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.

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

#include <stdio.h>

char *strcat_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;
    
    for( ; *dest != '\0' ; ++dest );
    while((( *dest++ = *src++ ) != '\0' ));
    
    return ret_ptr;
}

int main()
{
    char s1[30] = "stringA";
    char *s2 = "stringB";
    
    printf("result = %s\n",strcat_imp( s1 , s2 ));

    return 0;
}

 

Result : 

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