ft_strncmp

one·2021년 1월 8일
0

✅strncmp

  • 두 문자열의 일부문자들을 비교.
  • str1의 처음 num개의 문자와 str2의 처음 num개의 문자를 비교.
  • num개의 문자를 비교할 때까지 or NULL에 도달할 때까지 비교.

💾함수 원형

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

💻Parameters

  • str1, str2 : 비교할 문자열
  • num : 비교할 문자 개수

💻Return value

  • 같을 때 0
  • str1이 크면 양의 정수
  • str2가 크면 음의 정수

💾함수 구현

#include "libft.h"

int		ft_strncmp(const char* s1, const char* s2, size_t n)
{
	unsigned char* p1;
	unsigned char* p2;
	size_t			i;

	p1 = (unsigned char*)s1;
	p2 = (unsigned char*)s2;
	i = 0;
	while (n--)
	{
		if (p1[i] != p2[i] || p1[i] == 0 || p2[i] == 0)
			return (p1[i] - p2[i]);
		i++;
	}
	return (0);
}

💾사용 예시

#include <stdio.h>

int main()
{
    char s1[10] = "aaa";
    char s2[10] = "aab";

    int compare1 = ft_strncmp(s1, s2, 2);
    int compare2 = ft_strncmp(s2, s1, 4);
    int compare3 = ft_strncmp(s1, s2, 4);
    int compare4 = ft_strncmp(s1, s2, 0);

    printf("결과1 : %d\n", compare1);
    printf("결과2 : %d\n", compare2);
    printf("결과3 : %d\n", compare3);
    printf("결과4 : %d\n", compare4);

    return 0;
}

💡strcmp, memcmp

  • strcmp는 문자열 비교, memcmp는 두 메모리 블록 비교.
profile
늘 호기심을 갖고, 새로운 것에 도전할 것.

0개의 댓글