📌 매뉴얼 (Linux)
NAME
strnstr — locate a substring in a string
: 문자열에서 서브 문자열을 찾기
SYNOPSIS
#include <string.h>
char *strnstr(const char *big, const char *little, size_t len);
DESCRIPTION
The strnstr() function locates the first occurrence of the null-terminated string little in the
string big, where not more than len characters are searched. Characters that appear after a
‘\0’ character are not searched. Since the strnstr() function is a FreeBSD specific API, it
should only be used when portability is not a concern.
: strnstr() 함수는 len 길이 문자가 검색되는 문자열 big에서 null 종료 문자열의 첫 발생을 찾는다.
'\0' 문자 뒤의 문자는 검색되지 않는다.
RETURN VALUES
If little is an empty string, big is returned; if little occurs nowhere in big, NULL is re‐
turned; otherwise a pointer to the first character of the first occurrence of little is re‐
turned.
: little이 빈 문자열이면 big이 반환되고, big에서 little이 발생하지 않으면 NULL이 반환되며,
big에서 little이 발생하면 처음 발생하는 첫 문자에 대한 포인터를 반환한다.
📌 작성 코드
char *do_strnstr(const char *big, const char *little, size_t len)
{
size_t i;
size_t little_len;
i = 0;
little_len = do_strlen(little);
if (little_len == 0)
return ((char *)big);
while (i < len && big[i] != '\0')
{
if (big[i] == little[0] && little_len <= len - i)
{
if (do_strncmp(&big[i], little, little_len) == 0)
return ((char *)&big[i]);
}
i ++;
}
return (0);
}
📌 코드 리뷰
우선 little의 길이를 따로 구해두기 위해, strlen을 불러와 사용한다.
이 little_len의 값이 만약 0이라면, big을 반환한다고 매뉴얼에 적혀있듯이 따로 처리해주었다.
그리고 반복문을 돌게 되는데, big이 null을 만나거나 i를 len이 될 때까지 반복시키고 (big 전체X, big에서 len만큼만 탐색해준다.)
내부에서는 'little 문자열의 첫번째 부분(= little[0]) 과 big[i]가 같으며 남은 길이가 little의 길이보다 같거나 클 때' 의 조건에 맞으면
해당 위치부터 strncmp 과정을 거치고, 같다는 판별 (0)이 되면, 해당 big[i] 부분을 리턴해준다.
다를 경우는 다시 반복문을 돌아주는데, strncmp에서 바뀐 인덱스가 외부 반복문에는 적용되지 않기에
정상적으로 재탐색이 가능하다는 점이 strncmp를 쓰는 의의이다.
(처음에는 strncmp 없이 인덱스로 비교했는데, 같지 않으면 재탐색을 위해 인덱스를 초기화한다는 점에서 과정이 복잡했다.)
그렇게 little을 big에서 찾아주면 해당 위치를 반환하고, 못찾으면 0(NULL)을 반환하며 마무리 된다.
'프로그래밍 > C' 카테고리의 다른 글
[library] toupper 구현하기 (0) | 2024.05.13 |
---|---|
[library] strdup 구현하기 (0) | 2024.05.13 |
[library] strncmp 구현하기 (0) | 2024.05.10 |
[library] strrchr 구현하기 (0) | 2024.04.16 |
[study] 가변인자 (variable argument) (0) | 2024.04.03 |