TIL(Today I Learn)/C++
strchr, strnstr, strncmp 함수 구현
MinsoftK
2021. 1. 7. 19:00
틀린 내용이 있다면 댓글로 알려주세요! 감사합니다 :)
💡 strchr에 대하여
환경
- c, c++
- C에서는 <string.h>
- C++에서는
<cstring>
Prototype
char *ft_strchr(const char *str, int ch);
-
str
: c 형식 문자열 -
ch
: 검색할 문자로,int
형태로 형변환 되어서 전달되지만 함수 내부적으로는 다시char
형태로 처리된다.
Return Value
-
str
에서 검색한 문자가 가장 먼저 나타나는 곳을 가리키는 포인터를 리턴한다. 만일 문자가 없다면NULL
포인터를 리턴하게 된다.
strchr 함수의 구현
#include <string.h> //NULL과 size_t를 쓰기 위한 헤더
char *ft_strchr(const char *str, int ch)
{
int i;
char temp;
char *stemp;
i = 0;
temp = (char)ch;
stemp = (char *)str;
while (stemp[i] != temp)
{
if (stemp[i] == '\0')
return (NULL);
i++;
}
return (&stemp[i]);
}
return (NULL) 과 return (0)은 다르다. 착각했던 부분중 하나 void *function()일때와 매개변수에 const가 붙었을때는 형변환을 잘해줘야 한다.
💡 strnstr에 대하여
환경
-
c, c++
-
c에서는 <string.h>
-
c++에서는
<cstring>
Prototype
char *strnstr(const char *big, const char *little, size_t len);
big
: 전체 문자열little
: 전체 문자열big
에서 찾을 문자열little
len
:len
만큼의 길이에서 탐색을 한다.
strnstr 목적
- 이 함수는 strcmp와 거의 같다. 그러나
s1
,s2
의num
bytes의 값들을 비교한다는 점이 다르다.
Return Value
s1
,s2
의 n번째 byte의 비교한 값을 return 해준다.
strnstr 함수의 구현
#include <string.h> //NULL과 size_t를 쓰기 위한 헤더
char *ft_strnstr(const char *big, const char *little, size_t len)
{
size_t i;
size_t temp;
i = 0;
while (big[i] && i < len)
{
temp = 0;
if (little[temp] == big[i + temp])
{
while (little[temp] && big[i + temp])
{
if (little[temp] != big[i + temp] || (i + temp) >= len)
break ;
temp++;
}
if (little[temp] == '\0')
return (&((char *)big)[i]);
}
i++;
}
return ((void *)0);
}
💡 strncmp에 대하여
환경
-
c, c++
-
c에서는 <string.h>
-
c++에서는
<cstring>
Prototype
int strncmp(const char *s1 , const char *s2 , size_t n);
dest
: 비교할 문자열 s1src
: 비교할 문자열 s2size
:num
에서의 문자를 비교한다.
strncmp 목적
- 이 함수는 strcmp와 거의 같다. 그러나
s1
,s2
의num
bytes의 값들을 비교한다는 점이 다르다.
Return Value
s1
,s2
의 n번째 byte의 비교한 값을 return 해준다.
strncmp 함수의 구현
#include <string.h> //NULL과 size_t를 쓰기 위한 헤더
int ft_strncmp(const char *s1, const char *s2, size_t n)
{
size_t i;
i = 0;
while (s1[i] && s2[i] && i < n)
{
if (s1[i] != s2[i])
break ;
i++;
}
if (i == n)
return (0);
return ((unsigned char)s1[i] - (unsigned char)s2[i]); //확장형 아스키코드까지 생각하기에 unsigned char로 형변환
}
📕 reference :
728x90
반응형