[library] strncmp 구현하기

2024. 5. 10. 15:32·프로그래밍/C

📌 매뉴얼 (Linux)

더보기

NAME
       strncmp - compare two strings

: 문자열 비교하기


SYNOPSIS
       #include <string.h>
       int strncmp(const char *s1, const char *s2, size_t n);

DESCRIPTION
       The  strcmp()  function compares the two strings s1 and s2.  The locale
       is not taken into account (for  a  locale-aware  comparison,  see  str‐
       coll(3)).  The comparison is done using unsigned characters.
       strcmp() returns an integer indicating the result of the comparison, as
       follows:
       • 0, if the s1 and s2 are equal;
       • a negative value if s1 is less than s2;
       • a positive value if s1 is greater than s2.
       The strncmp() function is similar, except it compares  only  the  first
       (at most) n bytes of s1 and s2.

: strcmp 는 두 문자열 s1과 s2를 비교한다. 부호가 없는 문자 (unsigned characters)를 사용하여 수행한다.

s1과 s2가 같으면 0, s1이 s2보다 작으면 음수, s1이 s2보다 크면 양수.

strncmp 는 s1과 s2의 첫 번째 n 바이트만 비교한다는 점을 제외하고는 유사하다.


RETURN VALUE
       The strcmp() and strncmp() functions return an integer less than, equal
       to, or greater than zero if s1 (or the first n bytes thereof) is found,
       respectively, to be less than, to match, or be greater than s2.

: strncmp() 함수는 s1의 첫 n 바이트가 s2의 첫 n 바이트보다 작거나, 일치하거나,

또는 더 큰 것으로 발견되면 0보다 작거나, 같거나, 더 큰 정수를 반환한다.

 

📌 작성 코드

int	do_strncmp(const char *s1, const char *s2, size_t n)
{
	size_t	i;

	i = 0;
	while (i < n && (s1[i] != '\0' || s2[i] != '\0'))
	{
		if ((unsigned char) s1[i] != (unsigned char) s2[i])
			return ((unsigned char)s1[i] - (unsigned char)s2[i]);
		i ++;
	}
	return (0);
}

 

📌 코드 리뷰

strncmp 함수는 전체 문자열을 비교하는 strcmp와 다르게, 문자열의 첫 n바이트만 비교해주는 기능을 한다.

따라서, 인덱스 i를 반복문을 통해 특정 사이즈인 n까지만 동작하도록 해주고, 비교해주면서 다른 부분이 생기면

그때 s1에서 s2의 값을 빼 반환해준다. 이때 매뉴얼에서 언급한대로 unsigned char 를 통해 캐스팅한 값을 연산해주고,

이 값을 리턴해준다. 두 문자열이 같으면 0을 반환하기 때문에 반복문에서 다른점을 찾지 못하면 밖에서 0을 반환한다.

저작자표시 (새창열림)

'프로그래밍 > C' 카테고리의 다른 글

[library] strdup 구현하기  (0) 2024.05.13
[library] strnstr 구현하기  (0) 2024.05.10
[library] strrchr 구현하기  (0) 2024.04.16
[study] 가변인자 (variable argument)  (0) 2024.04.03
[library] strchr 구현하기  (0) 2024.03.30
'프로그래밍/C' 카테고리의 다른 글
  • [library] strdup 구현하기
  • [library] strnstr 구현하기
  • [library] strrchr 구현하기
  • [study] 가변인자 (variable argument)
doyoucode
doyoucode
  • doyoucode
    Do You Coding?
    doyoucode
  • 전체
    오늘
    어제
  • Programming Collection
    • 전체글 (73)
      • 프로그래밍 (69)
        • CS (7)
        • Algorithm (15)
        • C (43)
        • C++ (2)
        • Java (0)
        • Linux (2)
      • ETC (4)
        • 정보처리기사 (1)
        • TOEIC Speaking (0)
        • OPIc (0)
        • 영어 (2)
        • 특강, 컨퍼런스 (1)
  • hELLO· Designed By정상우.v4.10.3
doyoucode
[library] strncmp 구현하기
상단으로

티스토리툴바