프로그래밍/C
C] strstr, strcmp, strncmp, stricmp, strnicmp 함수 구현
eteo
2023. 9. 15. 23:08
strstr()
strstr() 함수는 문자열 내에서 부분 문자열(substring)을 검색하는 함수로 str1에서 str2를 찾아서, 첫 번째로 등장하는 위치의 포인터를 반환한다.
- str2의 길이가 0이면 str1 포인터 반환
- str2가 str1에서 발견되지 않으면 NULL 반환
- 찾은 경우 str1에서 str2가 시작되는 위치의 포인터 반환
const char* my_strstr(const char* str1, const char* str2) {
// 빈 문자열 검색 시 원본 문자열 반환
if (*str2 == '\0') {
return str1;
}
// 메인 검색 루프
for (; *str1 != '\0'; str1++) {
if (*str1 == *str2) { // 첫 문자가 일치하면
const char* s1 = str1;
const char* s2 = str2;
// 이후 문자들도 일치하는지 확인
while (*s1 == *s2 && *s2 != '\0') {
s1++;
s2++;
}
// str2의 끝까지 도달했다면 성공적으로 찾은 것
if (*s2 == '\0') {
return str1;
}
}
}
// 찾지 못한 경우 NULL 반환
return NULL;
}
strcmp()
두 문자열을 비교하여 사전순으로 어느 문자열이 더 앞서는지 판단한다.
- 0 : 두 문자열이 동일
- < 0 : 첫 번째 문자열이 더 앞섬
- > 0 : 두 번째 문자열이 더 앞섬
int my_strcmp(const char* s1, const char* s2)
{
while (*s1 && (*s1 == *s2)) {
s1++;
s2++;
}
return ((unsigned char)*s1) - ((unsigned char)*s2);
}
strcnmp()
두 문자열의 앞에서부터 n개의 문자만 비교한다.
int my_strncmp(const char* s1, const char* s2, int n)
{
while (n && *s1 && (*s1 == *s2)) {
s1++;
s2++;
n--;
}
if (n == 0)
return 0;
return ((unsigned char)*s1) - ((unsigned char)*s2);
}
stricmp() / strnicmp()
- stricmp : 대소문자를 구분하지 않고 두 문자열을 비교한다.
- strnicmp : 대소문자를 구분하지 않고 앞에서 부터 n개의 문자를 비교한다.
char my_tolower(char c) {
if (c >= 'A' && c <= 'Z') {
return c + ('a' - 'A');
}
return c;
}
int my_stricmp(const char* s1, const char* s2)
{
while (*s1 && *s2) {
int c1 = my_tolower((unsigned char)*s1);
int c2 = my_tolower((unsigned char)*s2);
if (c1 != c2)
return c1 - c2;
s1++;
s2++;
}
return my_tolower((unsigned char)*s1) - my_tolower((unsigned char)*s2);
}
int my_strnicmp(const char* s1, const char* s2, int n)
{
while (n && *s1 && *s2 &&
(my_tolower((unsigned char)*s1) == my_tolower((unsigned char)*s2))) {
s1++;
s2++;
n--;
}
if (n == 0)
return 0;
return my_tolower((unsigned char)*s1) - my_tolower((unsigned char)*s2);
}