strcmp : 2개의 문자열을 비교하는 함수

NAME
       strcmp, strncmp - compare two strings

SYNOPSIS
       #include <string.h>

       int strcmp(const char *s1, const char *s2);

       int strncmp(const char *s1, const char *s2, size_t n);

 

문자열의 길이를 비교하는것이 아니라 바이트 크기를 비교한다.

 

strcmp(const char *s1, const char *s2);

이러한데 리턴값은 아래와 같다.

s1 = s2 이면 0

s1 > s2 이면 -1

s1 < s2 이면 1

 

예제를 보면 이해하기 쉬울 것 같다.

 

#include 
#include 

int main()
{
    char *temp1 ="HPUX";
    char *temp2="LINUX";
    char *temp3 ="SOLARIS";

    printf("s1[%7s], s1[%7s]  ret =[%2d]\n", temp1, temp2, strcmp(temp1,temp2));
    printf("s2[%7s], s3[%7s]  ret =[%2d]\n", temp2, temp3,  strcmp(temp2,temp3));
    printf("s3[%7s], s1[%7s]  ret =[%2d]\n", temp3, temp1,  strcmp(temp3,temp1));

    return 0;
}
[ 결과 값 ] 
$ ./a.out 
s1[   HPUX], s1[  LINUX]  ret =[-1]
s2[  LINUX], s3[SOLARIS]  ret =[-1]
s3[SOLARIS], s1[   HPUX]  ret =[ 1]

 

 

원시함수 소스코드를

보면 어떤식으로 동작하는지 알 수 있다.

출처 : http://opensource.apple.com/source/Libc/Libc-262/ppc/gen/strcmp.c

 

#import 

/* This routine should be optimized. */

/* ANSI sez:
 *   The `strcmp' function compares the string pointed to by `s1' to the
 *   string pointed to by `s2'.
 *   The `strcmp' function returns an integer greater than, equal to, or less
 *   than zero, according as the string pointed to by `s1' is greater than,
 *   equal to, or less than the string pointed to by `s2'.  [4.11.4.2]
 */
int
strcmp(const char *s1, const char *s2)
{
    for ( ; *s1 == *s2; s1++, s2++)
	if (*s1 == '\0')
	    return 0;
    return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}

 

 

반응형

'Language > C' 카테고리의 다른 글

itoa 함수 예제  (7) 2012.10.17
strspn 함수 예제  (7) 2012.09.20
strchr 함수 예제  (7) 2012.08.14
strdup 함수 예제  (8) 2012.08.14
getutxent 함수 예제  (8) 2012.08.13

+ Recent posts