Create String Comparison Functions in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to create and implement custom string comparison functions in C. The lab covers understanding the built-in strcmp() function, implementing string comparison using conditional statements, handling case-insensitive comparisons, performing multiple string comparisons, and applying string comparison in a real-world scenario. By the end of this lab, you will have a strong understanding of string manipulation and comparison techniques in C programming.


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/UserInteractionGroup -.-> c/output("`Output`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/CompoundTypesGroup -.-> c/strings("`Strings`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/function_parameters("`Function Parameters`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") subgraph Lab Skills c/output -.-> lab-438244{{"`Create String Comparison Functions in C`"}} c/if_else -.-> lab-438244{{"`Create String Comparison Functions in C`"}} c/strings -.-> lab-438244{{"`Create String Comparison Functions in C`"}} c/user_input -.-> lab-438244{{"`Create String Comparison Functions in C`"}} c/function_parameters -.-> lab-438244{{"`Create String Comparison Functions in C`"}} c/function_declaration -.-> lab-438244{{"`Create String Comparison Functions in C`"}} end

Understand the strcmp() Function

In this step, you will learn about the strcmp() function in C, which is used to compare two strings lexicographically.

  1. Create a new file named string-compare.c in the ~/project directory:
cd ~/project
touch string-compare.c
  1. Open the file in WebIDE and add the following code:
#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. Compile and run the program:
gcc string-compare.c -o string-compare
./string-compare

Example output:

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

Let's break down how strcmp() works:

  • It returns 0 if the strings are exactly the same
  • It returns a negative value if the first string is lexicographically less than the second
  • It returns a positive value if the first string is lexicographically greater than the second

The function compares strings character by character until it finds a difference or reaches the end of one of the strings.

Implement String Comparison with if-else

In this step, you will learn how to use strcmp() with conditional statements to make decisions based on string comparisons.

  1. Create a new file named string-compare-conditional.c in the ~/project directory:
cd ~/project
touch string-compare-conditional.c
  1. Open the file in WebIDE and add the following code:
#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. Compile and run the program:
gcc string-compare-conditional.c -o string-compare-conditional
./string-compare-conditional

Example interaction:

Enter username: admin
Enter password: secret
Login successful!

Enter username: user
Enter password: wrongpass
Invalid username.

Key points about this example:

  • strcmp() is used inside if statements to check string equality
  • The function returns 0 when strings match exactly
  • Nested if-else statements allow for complex string comparison logic

Handle Case-insensitive Comparison

In this step, you will learn how to perform case-insensitive string comparisons using the strcasecmp() function.

  1. Create a new file named case-insensitive-compare.c in the ~/project directory:
cd ~/project
touch case-insensitive-compare.c
  1. Open the file in WebIDE and add the following code:
#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. Compile the program (note: you may need to use the -std=gnu99 flag):
gcc case-insensitive-compare.c -o case-insensitive-compare
  1. Run the program:
./case-insensitive-compare

Example interactions:

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.

Key points about case-insensitive comparison:

  • strcasecmp() compares strings ignoring case differences
  • It works similarly to strcmp(), but is case-insensitive
  • Useful for user inputs where case shouldn't matter

Perform Multiple String Comparisons

In this step, you will learn how to perform multiple string comparisons using different comparison techniques.

  1. Create a new file named multiple-string-compare.c in the ~/project directory:
cd ~/project
touch multiple-string-compare.c
  1. Open the file in WebIDE and add the following code:
#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. Compile the program:
gcc multiple-string-compare.c -o multiple-string-compare
  1. Run the program:
./multiple-string-compare

Example interactions:

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

Key points about multiple string comparisons:

  • Use strcmp() to compare different string combinations
  • Track the number of matching string pairs
  • Demonstrate flexible string comparison logic

Apply String Comparison in a Real-world Scenario

In this step, you will create a simple password management system that demonstrates practical string comparison techniques.

  1. Create a new file named password-manager.c in the ~/project directory:
cd ~/project
touch password-manager.c
  1. Open the file in WebIDE and add the following code:
#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. Compile the program:
gcc password-manager.c -o password-manager
  1. Run the program:
./password-manager

Example interactions:

=== 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.

Key points about this real-world scenario:

  • Uses strcmp() for secure credential verification
  • Demonstrates practical application of string comparison
  • Implements a simple authentication system
  • Shows how to compare multiple user credentials

Summary

In this lab, you learned about the strcmp() function in C, which is used to compare two strings lexicographically. You implemented string comparison using strcmp() and conditional statements to make decisions based on the comparison results. You also learned how to handle case-insensitive comparison and perform multiple string comparisons. Finally, you applied string comparison in a real-world scenario involving user authentication.

The key learning points from this lab include understanding the strcmp() function, implementing string comparison with if-else statements, handling case-insensitive comparison, and applying string comparison in a practical application.

Other C Tutorials you may like