1 개념[ | ]
- C Language strcmp()
- C언어 strcmp()
- 문자열을 비교하여 동일한지 여부 확인
- 헤더: string.h
2 문법[ | ]
정의
C
Copy
int strcmp(const char *s1, const char *s2);
비교 문자열 | 반환값 |
---|---|
같을 때 | 0 |
클 때 | 1 |
작을 때 | -1 |
두 문자열의 아스키코드 값을 비교하여 크고 작음을 판단
3 예시[ | ]
C
Copy
#include <stdio.h>
#include <string.h>
int main() {
char *str1 = "ab";
char *str2 = "ab";
char *str3 = "bc";
int r;
r = strcmp(str1, str2);
printf("%d\n", r); // 0
r = strcmp(str1, str3);
printf("%d\n", r); // -1
r = strcmp(str3, str1);
printf("%d\n", r); // 1
}
- → str1, str2는 문자열이 동일하여 결과값 0을 돌려줌
- → 반면 str1, str3은 str1의 첫 문자 'a'의 아스키 코드 값이 str3의 'b' 보다 작기 때문에 -1 이 출력됨
- → str3, str1은 그 반대인 1 이 출력됨
C
Copy
printf("%d\n", strcmp("ab", "ab")); // 0
printf("%d\n", strcmp("ab", "bc")); // -1
printf("%d\n", strcmp("bc", "ab")); // 1
- → "ab", "ab"는 문자열이 동일하여 결과값 0을 돌려줌
- → 반면 "ab", "bc"는 "ab"의 첫 문자 'a'의 아스키 코드 값이 "bc"의 'b' 보다 작기 때문에 -1 이 출력됨
- → "bc", "ab"는 그 반대인 1 이 출력됨
C
Copy
printf("%d\n", strcmp("hello", "hello")); // 0
printf("%d\n", strcmp("hello", "world")); // -1
printf("%d\n", strcmp("world", "hello")); // 1
4 같이 보기[ | ]
편집자 Jmnote Ykhwong Jmnote bot
로그인하시면 댓글을 쓸 수 있습니다.