C 언어에서 문자열 비교 함수 만들기

CBeginner
지금 연습하기

소개

이 랩에서는 C 언어에서 사용자 정의 문자열 비교 함수를 생성하고 구현하는 방법을 배우게 됩니다. 이 랩은 내장 함수 strcmp()의 이해, 조건문을 사용한 문자열 비교 구현, 대소문자를 구분하지 않는 비교 처리, 여러 문자열 비교 수행, 그리고 실제 시나리오에서 문자열 비교 적용을 다룹니다. 이 랩을 마치면 C 프로그래밍에서 문자열 조작 및 비교 기술에 대한 강력한 이해를 갖게 될 것입니다.

strcmp() 함수 이해하기

이 단계에서는 두 문자열을 사전식으로 비교하는 데 사용되는 C 언어의 strcmp() 함수에 대해 배우게 됩니다.

  1. ~/project 디렉토리에 string-compare.c라는 새 파일을 생성합니다.
cd ~/project
touch string-compare.c
  1. WebIDE 에서 파일을 열고 다음 코드를 추가합니다.
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "hello";
    char str2[] = "hello";
    char str3[] = "world";

    // Compare strings using strcmp()
    int result1 = strcmp(str1, str2);
    int result2 = strcmp(str1, str3);

    printf("Comparison between str1 and str2: %d\n", result1);
    printf("Comparison between str1 and str3: %d\n", result2);

    return 0;
}
  1. 프로그램을 컴파일하고 실행합니다.
gcc string-compare.c -o string-compare
./string-compare

예시 출력:

Comparison between str1 and str2: 0
Comparison between str1 and str3: -15

strcmp()가 어떻게 작동하는지 자세히 살펴보겠습니다.

  • 문자열이 정확히 동일하면 0 을 반환합니다.
  • 첫 번째 문자열이 두 번째 문자열보다 사전적으로 작으면 음수 값을 반환합니다.
  • 첫 번째 문자열이 두 번째 문자열보다 사전적으로 크면 양수 값을 반환합니다.

이 함수는 차이점을 찾거나 문자열 중 하나의 끝에 도달할 때까지 문자 단위로 문자열을 비교합니다.

if-else 문을 사용한 문자열 비교 구현

이 단계에서는 조건문을 사용하여 strcmp()를 활용하여 문자열 비교를 기반으로 결정을 내리는 방법을 배우게 됩니다.

  1. ~/project 디렉토리에 string-compare-conditional.c라는 새 파일을 생성합니다.
cd ~/project
touch string-compare-conditional.c
  1. WebIDE 에서 파일을 열고 다음 코드를 추가합니다.
#include <stdio.h>
#include <string.h>

int main() {
    char username[50];
    char password[50];

    printf("Enter username: ");
    scanf("%s", username);

    printf("Enter password: ");
    scanf("%s", password);

    // Compare username and password using if-else
    if (strcmp(username, "admin") == 0) {
        if (strcmp(password, "secret") == 0) {
            printf("Login successful!\n");
        } else {
            printf("Incorrect password.\n");
        }
    } else {
        printf("Invalid username.\n");
    }

    return 0;
}
  1. 프로그램을 컴파일하고 실행합니다.
gcc string-compare-conditional.c -o string-compare-conditional
./string-compare-conditional

예시 상호 작용:

Enter username: admin
Enter password: secret
Login successful!

Enter username: user
Enter password: wrongpass
Invalid username.

이 예제의 주요 사항:

  • strcmp()는 문자열의 동일성을 확인하기 위해 if 문 내에서 사용됩니다.
  • 문자열이 정확히 일치하면 함수는 0 을 반환합니다.
  • 중첩된 if-else 문은 복잡한 문자열 비교 로직을 허용합니다.

대소문자 구분 없는 비교 처리

이 단계에서는 strcasecmp() 함수를 사용하여 대소문자를 구분하지 않는 문자열 비교를 수행하는 방법을 배우게 됩니다.

  1. ~/project 디렉토리에 case-insensitive-compare.c라는 새 파일을 생성합니다.
cd ~/project
touch case-insensitive-compare.c
  1. WebIDE 에서 파일을 열고 다음 코드를 추가합니다.
#include <stdio.h>
#include <string.h>

int main() {
    char input[50];

    printf("Enter a color (Red/red/GREEN/green): ");
    scanf("%s", input);

    // Case-insensitive comparison
    if (strcasecmp(input, "red") == 0) {
        printf("You entered the color RED.\n");
    } else if (strcasecmp(input, "green") == 0) {
        printf("You entered the color GREEN.\n");
    } else if (strcasecmp(input, "blue") == 0) {
        printf("You entered the color BLUE.\n");
    } else {
        printf("Unknown color.\n");
    }

    return 0;
}
  1. 프로그램을 컴파일합니다 (참고: -std=gnu99 플래그를 사용해야 할 수 있습니다).
gcc case-insensitive-compare.c -o case-insensitive-compare
  1. 프로그램을 실행합니다.
./case-insensitive-compare

예시 상호 작용:

Enter a color (Red/red/GREEN/green): RED
You entered the color RED.

Enter a color (Red/red/GREEN/green): green
You entered the color GREEN.

대소문자를 구분하지 않는 비교에 대한 주요 사항:

  • strcasecmp()는 대소문자 차이를 무시하고 문자열을 비교합니다.
  • strcmp()와 유사하게 작동하지만 대소문자를 구분하지 않습니다.
  • 대소문자가 중요하지 않은 사용자 입력에 유용합니다.

다중 문자열 비교 수행

이 단계에서는 다양한 비교 기술을 사용하여 여러 문자열 비교를 수행하는 방법을 배우게 됩니다.

  1. ~/project 디렉토리에 multiple-string-compare.c라는 새 파일을 생성합니다.
cd ~/project
touch multiple-string-compare.c
  1. WebIDE 에서 파일을 열고 다음 코드를 추가합니다.
#include <stdio.h>
#include <string.h>

int main() {
    char input[3][50];
    int comparison_count = 0;

    // Input three strings
    for (int i = 0; i < 3; i++) {
        printf("Enter string %d: ", i + 1);
        scanf("%s", input[i]);
    }

    // Compare first two strings
    if (strcmp(input[0], input[1]) == 0) {
        printf("First two strings are identical.\n");
        comparison_count++;
    }

    // Compare last two strings
    if (strcmp(input[1], input[2]) == 0) {
        printf("Last two strings are identical.\n");
        comparison_count++;
    }

    // Compare first and last strings
    if (strcmp(input[0], input[2]) == 0) {
        printf("First and last strings are identical.\n");
        comparison_count++;
    }

    // Overall comparison summary
    printf("Total matching string pairs: %d\n", comparison_count);

    return 0;
}
  1. 프로그램을 컴파일합니다.
gcc multiple-string-compare.c -o multiple-string-compare
  1. 프로그램을 실행합니다.
./multiple-string-compare

예시 상호 작용:

Enter string 1: hello
Enter string 2: world
Enter string 3: hello
Total matching string pairs: 1

여러 문자열 비교에 대한 주요 사항:

  • strcmp()를 사용하여 다양한 문자열 조합을 비교합니다.
  • 일치하는 문자열 쌍의 수를 추적합니다.
  • 유연한 문자열 비교 로직을 보여줍니다.

실제 시나리오에서 문자열 비교 적용

이 단계에서는 실용적인 문자열 비교 기술을 보여주는 간단한 비밀번호 관리 시스템을 만들 것입니다.

  1. ~/project 디렉토리에 password-manager.c라는 새 파일을 생성합니다.
cd ~/project
touch password-manager.c
  1. WebIDE 에서 파일을 열고 다음 코드를 추가합니다.
#include <stdio.h>
#include <string.h>

#define MAX_USERS 3
#define MAX_USERNAME 50
#define MAX_PASSWORD 50

// User structure to store credentials
struct User {
    char username[MAX_USERNAME];
    char password[MAX_PASSWORD];
    char role[20];
};

int main() {
    // Predefined user database
    struct User users[MAX_USERS] = {
        {"admin", "admin123", "administrator"},
        {"manager", "manager456", "manager"},
        {"user", "user789", "regular"}
    };

    char input_username[MAX_USERNAME];
    char input_password[MAX_PASSWORD];
    int login_success = 0;

    printf("=== Simple Password Management System ===\n");
    printf("Enter username: ");
    scanf("%s", input_username);

    printf("Enter password: ");
    scanf("%s", input_password);

    // Authenticate user with string comparison
    for (int i = 0; i < MAX_USERS; i++) {
        if (strcmp(users[i].username, input_username) == 0) {
            if (strcmp(users[i].password, input_password) == 0) {
                printf("Login Successful!\n");
                printf("Role: %s\n", users[i].role);
                login_success = 1;
                break;
            }
        }
    }

    if (!login_success) {
        printf("Login Failed. Invalid username or password.\n");
    }

    return 0;
}
  1. 프로그램을 컴파일합니다.
gcc password-manager.c -o password-manager
  1. 프로그램을 실행합니다.
./password-manager

예시 상호 작용:

=== Simple Password Management System ===
Enter username: admin
Enter password: admin123
Login Successful!
Role: administrator

Enter username: user
Enter password: wrongpassword
Login Failed. Invalid username or password.

이 실제 시나리오에 대한 주요 사항:

  • 안전한 자격 증명 확인을 위해 strcmp()를 사용합니다.
  • 문자열 비교의 실용적인 적용을 보여줍니다.
  • 간단한 인증 시스템을 구현합니다.
  • 여러 사용자 자격 증명을 비교하는 방법을 보여줍니다.

요약

이 랩에서는 두 문자열을 사전식으로 비교하는 데 사용되는 C 의 strcmp() 함수에 대해 배웠습니다. strcmp()와 조건문을 사용하여 문자열 비교를 구현하고 비교 결과에 따라 결정을 내렸습니다. 또한 대소문자를 구분하지 않는 비교를 처리하고 여러 문자열 비교를 수행하는 방법을 배웠습니다. 마지막으로 사용자 인증과 관련된 실제 시나리오에서 문자열 비교를 적용했습니다.

이 랩에서 얻은 주요 학습 내용은 strcmp() 함수 이해, if-else 문을 사용한 문자열 비교 구현, 대소문자를 구분하지 않는 비교 처리, 실용적인 응용 프로그램에서 문자열 비교 적용 등이 있습니다.