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

C언어 길이 만큼 문자열 비교 함수 strncmp()

· 댓글개 · 바다야크

C함수 길이 만큼 문자열 비교 strncmp()

strncmp()는 2개의 문자열을 2개의 문자열을 지정한 문자 개수까지만 비교합니다.

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

C언어 strncmp() 함수 예제

#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  , strncmp( str_apple, str_apple  , 5) );
   printf( "%s with %s = %d\n", str_apple, str_apple2 , strncmp( str_apple, str_apple2 , 5) );
   printf( "%s with %s = %d\n", str_apple, str_banana , strncmp( str_apple, str_banana , 5) );
   printf( "%s with %s = %d\n", str_apple, str_appleII, strncmp( str_apple, str_appleII, 5) );

   return 0;
}

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

]$ ./a.out
apple with apple = 0
apple with    apple = 65
apple with banana = -1
apple with appleII = 0
]$
SNS 공유하기
💬 댓글 개
최근글
이모티콘창 닫기
울음
안녕
감사해요
당황
피폐

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