C 言語で文字列比較関数を作成する

CCBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、C言語でカスタムの文字列比較関数を作成して実装する方法を学びます。この実験では、組み込みのstrcmp()関数の理解、条件文を使った文字列比較の実装、大文字小文字を区別しない比較の処理、複数の文字列比較の実行、および現実世界のシナリオでの文字列比較の適用について説明します。この実験が終了するとき、C言語プログラミングにおける文字列操作と比較技術を十分に理解していることになります。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/CompoundTypesGroup(["Compound Types"]) c(("C")) -.-> c/FunctionsGroup(["Functions"]) c/ControlFlowGroup -.-> c/if_else("If...Else") c/CompoundTypesGroup -.-> c/strings("Strings") c/FunctionsGroup -.-> c/function_declaration("Function Declaration") c/FunctionsGroup -.-> c/function_parameters("Function Parameters") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/if_else -.-> lab-438244{{"C 言語で文字列比較関数を作成する"}} c/strings -.-> lab-438244{{"C 言語で文字列比較関数を作成する"}} c/function_declaration -.-> lab-438244{{"C 言語で文字列比較関数を作成する"}} c/function_parameters -.-> lab-438244{{"C 言語で文字列比較関数を作成する"}} c/user_input -.-> lab-438244{{"C 言語で文字列比較関数を作成する"}} c/output -.-> lab-438244{{"C 言語で文字列比較関数を作成する"}} end

strcmp()関数を理解する

このステップでは、C言語のstrcmp()関数について学びます。この関数は、辞書順に2つの文字列を比較するために使用されます。

  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";

    // 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を返します。
  • 最初の文字列が辞書順で2番目の文字列より小さい場合、負の値を返します。
  • 最初の文字列が辞書順で2番目の文字列より大きい場合、正の値を返します。

この関数は、文字列の違いを見つけるか、どちらかの文字列の終端に達するまで、1文字ずつ文字列を比較します。

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);

    // if-elseを使ってusernameとpasswordを比較
    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);

    // 大文字小文字を区別しない比較
    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;

    // 3つの文字列を入力
    for (int i = 0; i < 3; i++) {
        printf("Enter string %d: ", i + 1);
        scanf("%s", input[i]);
    }

    // 最初の2つの文字列を比較
    if (strcmp(input[0], input[1]) == 0) {
        printf("最初の2つの文字列は同じです。\n");
        comparison_count++;
    }

    // 最後の2つの文字列を比較
    if (strcmp(input[1], input[2]) == 0) {
        printf("最後の2つの文字列は同じです。\n");
        comparison_count++;
    }

    // 最初と最後の文字列を比較
    if (strcmp(input[0], input[2]) == 0) {
        printf("最初と最後の文字列は同じです。\n");
        comparison_count++;
    }

    // 全体的な比較の要約
    printf("一致する文字列のペアの合計数: %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
一致する文字列のペアの合計数: 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

// 資格情報を格納するためのユーザ構造体
struct User {
    char username[MAX_USERNAME];
    char password[MAX_PASSWORD];
    char role[20];
};

int main() {
    // 事前に定義されたユーザデータベース
    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("=== 簡単なパスワード管理システム ===\n");
    printf("ユーザ名を入力してください: ");
    scanf("%s", input_username);

    printf("パスワードを入力してください: ");
    scanf("%s", input_password);

    // 文字列比較を使ってユーザを認証する
    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("ログイン成功!\n");
                printf("役割: %s\n", users[i].role);
                login_success = 1;
                break;
            }
        }
    }

    if (!login_success) {
        printf("ログイン失敗。ユーザ名またはパスワードが間違っています。\n");
    }

    return 0;
}
  1. プログラムをコンパイルします。
gcc password-manager.c -o password-manager
  1. プログラムを実行します。
./password-manager

実行例:

=== 簡単なパスワード管理システム ===
ユーザ名を入力してください: admin
パスワードを入力してください: admin123
ログイン成功!
役割: administrator

ユーザ名を入力してください: user
パスワードを入力してください: wrongpassword
ログイン失敗。ユーザ名またはパスワードが間違っています。

この現実世界のシナリオのポイント:

  • セキュアな資格情報の検証にstrcmp()を使用しています。
  • 文字列比較の実際の応用を示しています。
  • 簡単な認証システムを実装しています。
  • 複数のユーザの資格情報を比較する方法を示しています。

まとめ

この実験では、C言語のstrcmp()関数について学びました。この関数は、辞書式順序で2つの文字列を比較するために使用されます。strcmp()と条件文を使って文字列比較を実装し、比較結果に基づいて判断を行いました。また、大文字小文字を区別しない比較を行う方法と、複数の文字列比較を行う方法についても学びました。最後に、ユーザ認証に関する現実世界のシナリオで文字列比較を適用しました。

この実験からの主な学びは、strcmp()関数の理解、if-else文を使った文字列比較の実装、大文字小文字を区別しない比較の処理、および実際のアプリケーションでの文字列比較の適用です。