본문으로 바로가기
homeimage
  1. Home
  2. 컴퓨터/프로그래밍
  3. C언어 문자열 비교 함수 strcmp()

C언어 문자열 비교 함수 strcmp()

· 댓글개 · 바다야크

C함수 문자열 비교 strcmp()

strcmp는 2개의 문자열을 비교하는 함수이며, 문자열의 길이가 크고 작음을 비교하는 것이 아니라 첫번재 문자부터 차례로 바이트의 크기를 비교합니다.

  • 헤더: string.h
  • 형태: char * strcmp( const char *s1, const char *s2)
  • 인수: char *s1 비교할 대상 문자열
    char *s2 비교할 문자열
  • 반환: 0 == 결과 값이면 s1 = s2
    0 < 결과 값이면 s1 > s2
    0 > 결과 값이면 s1 < s2

C언어 strcmp() 함수 예제

#include <stdio.h>
#include <string.h>

int main( void)
{
   char  str_apple[]  = "apple";
   char  str_apple2[] = "   apple";
   char  str_banana[] = "banana";
   char  str_appleII[]= "appleII";
                     
   printf( "%s with %s = %d\n", str_apple, str_apple  , strcmp( str_apple, str_apple  ) );
   printf( "%s with %s = %d\n", str_apple, str_apple2 , strcmp( str_apple, str_apple2 ) );
   printf( "%s with %s = %d\n", str_apple, str_banana , strcmp( str_apple, str_banana ) );
   printf( "%s with %s = %d\n", str_apple, str_appleII, strcmp( str_apple, str_appleII) );

   return 0;
}

C언어 strcmp() 예제 실행 결과

]$ ./a.out
apple with apple = 0
apple with    apple = 65   <- 공백이 있는 문자열이 더 길지만 공백문자가 'a'보다 작음
apple with banana = -1
apple with appleII = -73
]$
SNS 공유하기
💬 댓글 개
최근글
이모티콘창 닫기
울음
안녕
감사해요
당황
피폐

이모티콘을 클릭하면 댓글창에 입력됩니다.