본문 바로가기

프로그래밍/C언어

[DGPD][C언어] 문자열 비교 함수 strcmp 만들기.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
 
int myStrcmp(const char* str1, const char* str2)
{
    while (*str1 != '\0' || *str2 != 0)
    {
        if (*str1 > * str2)
        {
            return 1;
        }
        
        if (*str1 < *str2)
        {
            return -1;
        }
        
        str1++;
        str2++;
    }
 
    return 0;
}
 
int main()
{
    char key[] = "apple";
    char buffer[80];
 
    do {
        printf("Guess my favorite fruit? ");
        fflush(stdout);
        scanf("%79s", buffer);
    } while (myStrcmp(key, buffer) != 0);
 
    puts("Correct answer!");
 
    return 0;
}
cs