C 언어 문자열 비교 strcmp, strncmp 사용법

두 개의 문자열이 같은지 판단할 수 있는 strcmp와 strncmp 함수 사용법을 알아보겠습니다.

두 함수의 차이는 문자 개수를 지정하는 경우와 또는 지정하지 않은 경우에 따라 사용하는 함수가 달라집니다.

 

strcmp

먼저 strcmp 함수 사용방법을 알아보겠습니다.

int strcmp(const char* str1, const char* str2)

첫 번째 파라미터 str1 : 비교 문자열1
두 번째 파라미터 str2 : 비교 문자열2

 

strcmp 함수에는 비교할 문자열 2개를 파라미터로 지정합니다.

두 개의 문자열을 비교해 문자열이 같다면 0을 반환하고, 다르면 0 이외의 값인 음수 혹은 양수를 반환합니다.

str1 == str2 경우 0을 반환
str1 < str2 경우 음수 반환 
str1 > str2 경우 양수 반환 

 

#include<string.h>
#include<stdio.h>
 
int main()
{
    const char* str1 = "BlockDMask";
    const char* str2 = "Block";
    const char* str3 = "BlockDMask";
    const char* str4 = "BlockFMask";
    const char* str5 = "BlockAMask";
    const char* str6 = "BlockAMa";
    
    //문자열 비교 반환값 확인
    printf("strcmp(%s, %s)\t = %d\n", str1, str2, strcmp(str1, str2));
    printf("strcmp(%s, %s)\t = %d\n", str1, str3, strcmp(str1, str3));
    printf("strcmp(%s, %s)\t = %d\n", str1, str4, strcmp(str1, str4));
    printf("strcmp(%s, %s)\t = %d\n", str1, str5, strcmp(str1, str5));
    printf("strcmp(%s, %s)\t = %d\n", str6, str1, strcmp(str6, str1));

 
    //문자열이 같은지를 판단할때 사용
    if (strcmp(str1, str2) == 0)
    {
        printf("if문 판정 결과 %s, %s 는 같습니다.", str1, str2);
    }
    else
    {
        printf("if문 판정 결과 %s, %s 는 다릅니다.", str1, str2);
    }
 
    return 0;
}

 

결과

strcmp(BlockDMask, Block)	 = 1
strcmp(BlockDMask, BlockDMask)	 = 0
strcmp(BlockDMask, BlockFMask)	 = -1
strcmp(BlockDMask, BlockAMask)	 = 1
strcmp(BlockAMa, BlockDMask)	 = -1
if문 판정 결과 BlockDMask, Block 는 다릅니다.

 

문자열이 같은 경우에는 0을 반환하고 같지 않은 경우에는 0 이외의 값을 반환했습니다.

첫 번째 파라미터 문자열이 긴 경우에는 양수 1을 반환했습니다.

두 번째 파라미터 문자열이 긴 경우에는 음수 -1을 반환했습니다.

 

strncmp

비교하고 싶은 문자열 길이를 지정하고 싶은 경우에는 strncmp 함수를 사용합니다.

int strncmp(const char* str1, const char* str2, size_t n);

첫 번째 파라미터 str1 : 비교 문자열1
두 번째 파라미터 str2 : 비교 문자열2
세 번째 파라미터 n : 비교 문자열 범위

 

문자열 비교 범위는 0보다 큰 값을 지정해야 합니다.

0을 지정하는 경우에는 결과적으로 문자열을 비교하지 않습니다.

비교하고 싶은 길이가 0이기 때문입니다.

마이너스 값을 지정한 경우에는 언더플로우가 발생해 문자열을 끝까지 비교합니다.

마지막으로 문자열 길이보다 큰 수를 지정한 경우에는 문자열 최대 길이까지 비교합니다.

#include <stdio.h>
#include <string.h>
int main()
{
    char s1[10] = "aaa";
    char s2[10] = "aab";

    int compare1 = strncmp(s1, s2, 2);
    int compare2 = strncmp(s2, s1, 2);
    int compare3 = strncmp(s1, s2, 3);
    int compare4 = strncmp(s1, s2, 100);
    
    printf("결과1 : %d\n",compare1); 
    printf("결과2 : %d\n",compare2);
    printf("결과3 : %d\n",compare3);
    printf("결과4 : %d\n",compare4);


    return 0;
}

 

결과 1은 2번째 변수 s1과 s2의 2번째 문자열까지 비교합니다.

변수 s1과 s2의 2번째 문자열 까지는 aa로 같기 때문에 0을 반환합니다.

결과 2는 변수 s1과 s2를 바꿔서 실행한 결과입니다.

결과 3은 문자열 길이만큼 범위를 지정했습니다.

마지막 문자열이 다르기 때문에 1을 반환합니다.

결과 4는 문자열 길이보다 큰 범위를 지정했기 때문에 문자열 전체 길이만큼 비교를 했습니다.

댓글