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
]$
'컴퓨터 > 프로그래밍' 카테고리의 다른 글
C언어 길이 만큼 문자열 비교 함수 strncmp() (0) | 2020.03.15 |
---|---|
C언어 길이를 지정하여 두 개의 문자열 합침 함수 strncat() (0) | 2020.03.15 |
C언어 두개의 문자열을 합침 함수 strcat() (0) | 2020.03.15 |