C Program To Compare Two Strings

6 min read

C Program to Compare Two Strings: A Complete Guide

Comparing two strings in C is a fundamental operation that every programmer should master. Whether you're building a text editor, a search engine, or a simple command-line utility, understanding how to compare strings effectively is essential. In this full breakdown, we'll explore multiple methods to compare two strings in C, from using built-in library functions to implementing custom solutions.

Not obvious, but once you see it — you'll see it everywhere.

Introduction to String Comparison in C

In C programming, a string is essentially an array of characters terminated by a null character (\0). When we talk about comparing two strings, we're determining whether they are equal, or if one comes before or after the other in lexicographical order. This operation is crucial for sorting algorithms, data validation, and many other applications.

The C standard library provides several functions for string comparison, with strcmp() being the most commonly used. Even so, understanding how these functions work internally can help you write more efficient and dependable code Less friction, more output..

Method 1: Using the strcmp() Function

The strcmp() function from the <string.h> library is the most straightforward way to compare two strings in C. It compares strings character by character until it finds a difference or reaches the end of both strings Most people skip this — try not to..

#include 
#include 

int main() {
    char str1[100], str2[100];
    
    printf("Enter first string: ");
    fgets(str1, 100, stdin);
    
    printf("Enter second string: ");
    fgets(str2, 100, stdin);
    
    // Remove newline characters if present
    str1[strcspn(str1, "\n")] = 0;
    str2[strcspn(str2, "\n")] = 0;
    
    int result = strcmp(str1, str2);
    
    if (result == 0) {
        printf("Strings are equal\n");
    } else if (result < 0) {
        printf("First string comes before second string\n");
    } else {
        printf("First string comes after second string\n");
    }
    
    return 0;
}

How strcmp() works:

  • Returns 0 if both strings are identical
  • Returns a negative value if the first string comes before the second
  • Returns a positive value if the first string comes after the second

The comparison is case-sensitive, meaning 'A' and 'a' are considered different characters The details matter here. Which is the point..

Method 2: Case-Insensitive String Comparison

For many applications, you might need to compare strings without considering case. The strcasecmp() function (POSIX) or strcmpi() function (some compilers) can be used for this purpose Simple as that..

#include 
#include 

#ifdef _WIN32
    #define STRCASECMP strcmpi
#else
    #define STRCASECMP strcasecmp
#endif

int main() {
    char str1[100], str2[100];
    
    printf("Enter first string: ");
    fgets(str1, 100, stdin);
    
    printf("Enter second string: ");
    fgets(str2, 100, stdin);
    
    // Remove newline characters
    str1[strcspn(str1, "\n")] = 0;
    str2[strcspn(str2, "\n")] = 0;
    
    int result = STRCASECMP(str1, str2);
    
    if (result == 0) {
        printf("Strings are equal (case-insensitive)\n");
    } else if (result < 0) {
        printf("First string comes before second string\n");
    } else {
        printf("First string comes after second string\n");
    }
    
    return 0;
}

Method 3: Manual String Comparison Implementation

Understanding how string comparison works internally is valuable for learning purposes. Here's a manual implementation that mimics the behavior of strcmp():

#include 

int manual_strcmp(const char *str1, const char *str2) {
    // Loop through both strings simultaneously
    while (*str1 && *str2 && *str1 == *str2) {
        str1++;
        str2++;
    }
    
    // Return difference between ASCII values
    return *(unsigned char *)str1 - *(unsigned char *)str2;
}

Easier said than done, but still worth knowing.

int main() {
    char str1[100], str2[100];
    
    printf("Enter first string: ");
    fgets(str1, 100, stdin);
    
    printf("Enter second string: ");
    fgets(str2, 100, stdin);
    
    // Remove newline characters
    int i;
    for (i = 0; str1[i] !And = '\0' && str1[i] ! = '\n'; i++);
    str1[i] = '\0';
    
    for (i = 0; str2[i] != '\0' && str2[i] !

## Method 4: Using strncmp() for Partial Comparison

Sometimes you need to compare only the first N characters of two strings. The `strncmp()` function is perfect for this scenario:

```c
#include 
#include 

int main() {
    char str1[100], str2[100];
    int n;
    
    printf("Enter first string: ");
    fgets(str1, 100, stdin);
    
    printf("Enter second string: ");
    fgets(str2, 100, stdin);
    
    printf("Enter number of characters to compare: ");
    scanf("%d", &n);
    
    // Remove newline characters
    str1[strcspn(str1, "\n")] = 0;
    str2[strcspn(str2, "\n")] = 0;
    
    int result = strncmp(str1, str2, n);
    
    if (result == 0) {
        printf("First %d characters are equal\n", n);
    } else if (result < 0) {
        printf("First string is lexicographically smaller\n");
    } else {
        printf("First string is lexicographically larger\n");
    }
    
    return 0;
}

Complete Program with Menu Options

Here's a comprehensive program that demonstrates all the comparison methods with a user-friendly menu:

#include 
#include 

#ifdef _WIN32
    #define STRCASECMP strcmpi
#else
    #define STRCASECMP strcasecmp
#endif

int manual_strcmp(const char *str1, const char *str2) {
    while (*str1 && *str2 && *str1 == *str2) {
        str1++;
        str2++;
    }
    return *(unsigned char *)str1 - *(unsigned char *)str2;
}

void remove_newline(char *str) {
    int len = strlen(str);
    if (len > 0 && str[len-1] == '\n') {
        str[len-1] = '\0';
    }
}

int main() {
    char str1[200], str2[200];
    int choice, n;
    
    printf("=== String Comparison Program ===\n");
    printf("Enter first string: ");

```c
#include 
#include 
#include 

#ifdef _WIN32
    #define STRCASECMP strcmpi
#else
    #define STRCASECMP strcasecmp
#endif

int manual_strcmp(const char *str1, const char *str2) {
    while (*str1 && *str2 && *str1 == *str2) {
        str1++;
        str2++;
    }
    return *(unsigned char *)str1 - *(unsigned char *)str2;
}

void remove_newline(char *str) {
    int len = strlen(str);
    if (len > 0 && str[len-1] == '\n') {
        str[len-1] = '\0';
    }
}

void compare_manual() {
    char str1[200], str2[200];
    
    printf("Enter first string: ");
    fgets(str1, 200, stdin);
    remove_newline(str1);
    
    printf("Enter second string: ");
    fgets(str2, 200, stdin);
    remove_newline(str2);
    
    int result = manual_strcmp(str1, str2);
    
    printf("Manual Comparison Result: ");
    if (result == 0) {
        printf("Strings are equal\n");
    } else if (result < 0) {
        printf("First string comes before second string\n");
    } else {
        printf("First string comes after second string\n");
    }
}

void compare_case_insensitive() {
    char str1[200], str2[200];
    
    printf("Enter first string: ");
    fgets(str1, 200, stdin);
    remove_newline(str1);
    
    printf("Enter second string: ");
    fgets(str2, 200, stdin);
    remove_newline(str2);
    
    int result = STRCASECMP(str1, str2);
    
    printf("Case-Insensitive Comparison Result: ");
    if (result == 0) {
        printf("Strings are equal (ignoring case)\n");
    } else if (result < 0) {
        printf("First string comes before second string (ignoring case)\n");
    } else {
        printf("First string comes after second string (ignoring case)\n");
    }
}

void compare_partial() {
    char str1[200], str2[200];
    int n;
    
    printf("Enter first string: ");
    fgets(str1, 200, stdin);
    remove_newline(str1);
    
    printf("Enter second string: ");
    fgets(str2, 200, stdin);
    remove_newline(str2);
    
    printf("Enter number of characters to compare: ");
    scanf("%d", &n);
    
    if (n < 0) {
        printf("Number of characters cannot be negative!\n");
        return;
    }
    
    int result = strncmp(str1, str2, n);
    
    printf("Partial Comparison Result (first %d characters): ", n);
    if (result == 0) {
        printf("First %d characters are equal\n", n);
    } else if (result < 0) {
        printf("First string is lexicographically smaller\n");
    } else {
        printf("First string is lexicographically larger\n");
    }
}

void display_menu() {
    printf("\n=== String Comparison Program ===\n");
    printf("1. Manual Comparison (Case-Sensitive)\n");
    printf("2. Case-Insensitive Comparison\n");
    printf("3. Partial Comparison (First N characters)\n");
    printf("4. 

int main() {
    char str1[200], str2[200];
    int choice, n;
    int running = 1;
    
    printf("=== Enhanced String Comparison Program ===\n");
    
    while (running) {
        display_menu();
        scanf("%d", &choice);
        getchar(); // Clear the newline character from input buffer
        
        switch (choice) {
            case 1:
                compare_manual();
                break;
                
            case 2:
                compare_case_insensitive();
                break;
                
            case 3:
                compare_partial();
                break;
                
            case 4:
                printf("Thank you for using the String Comparison Program!That said, \n");
                running = 0;
                break;
                
            default:
                printf("Invalid choice! Please enter a number between 1 and 4.
Up Next

Just In

Cut from the Same Cloth

Parallel Reading

Thank you for reading about C Program To Compare Two Strings. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home