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

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

part 3 - strcmp (string compare)

Function Name : strcmp

Definition : This function starts comparing the first character of each string.
    If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

Prototype : int strcmp (const char *destination, const char *source );

#include <stdio.h>

int strcmp_imp ( const char *dest , const char *src )
{   
    if(( dest == NULL ) || ( src == NULL ))
    {
        printf("[%d %s] Invalid input string!!",__LINE__,__FUNCTION__);
        return 2;
    }

    int i = 0;
    while( dest[i] == src[i] )
    {
        if( dest[i] == '\0' )
            return 0;
        ++i;
    }
    return ( dest[i] > src[i] ? 1 : -1 );
}

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

    return 0;
}

 

Result :

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

回傳的結果可以依照要求自行做定義。