Compare Two Strings in C Programming

In C programming, a string is essentially a sequence of characters terminated by a null character '\0'. Strings are widely used for text processing, data storage, and manipulation. One common operation on strings is comparison, where you determine whether two strings are identical or which one comes first alphabetically.

Comparing strings in C can be performed using the built-in `strcmp()` function from the `string.h` library, or manually by iterating through each character using pointers. This tutorial provides a comprehensive explanation of both methods, including the theory, algorithms, and practical C programs.

Understanding string comparison is important because strings are not primitive data types in C. Unlike integers or characters, you cannot simply use the '==' operator to compare strings, as that compares the memory addresses, not the content of the strings.

Why Compare Strings in C?

String comparison is an essential operation in programming for tasks such as:

- Sorting a list of names or words alphabetically.

- Searching for a specific string in a database or array of strings.

- Validating user input or passwords.

- Implementing text-based algorithms or processing textual data.

In C, since strings are arrays of characters, comparison requires examining each character individually until a difference is found or the end of the string is reached.

1. Method 1: Using strcmp() Function

The `strcmp()` function in C compares two strings lexicographically. Its syntax is:

int strcmp(const char *str1, const char *str2);

The function returns an integer value based on the comparison:

- `0` → Both strings are equal.

- `<0` → str1 is less than str2 (appears before in dictionary order).

- `>0` → str1 is greater than str2 (appears after in dictionary order).

Example of using `strcmp()` in a C program is provided below.

Algorithm Using strcmp()

Step 1: Start the program.

Step 2: Include the necessary header files (`stdio.h` and `string.h`).

Step 3: Declare two character arrays to store the strings.

Step 4: Input the strings from the user.

Step 5: Call `strcmp(str1, str2)` and store the result in a variable.

Step 6: Analyze the result:

- If result = 0 → strings are equal.

- If result < 0 → first string is smaller.

- If result > 0 → first string is greater.

Step 7: Print the comparison result.

Step 8: End the program.

C Program Using strcmp()

C
Compare two strings using strcmp() function
#include <stdio.h>
#include <string.h>

int main() {
    char str1[100], str2[100];
    int result;

    printf("Enter first string: ");
    fgets(str1, sizeof(str1), stdin);
    if(str1[strlen(str1)-1] == '\n') str1[strlen(str1)-1] = '\0';

    printf("Enter second string: ");
    fgets(str2, sizeof(str2), stdin);
    if(str2[strlen(str2)-1] == '\n') str2[strlen(str2)-1] = '\0';

    result = strcmp(str1, str2);

    if(result == 0) {
        printf("Both strings are equal.\n");
    } else if(result < 0) {
        printf("First string is smaller than second string.\n");
    } else {
        printf("First string is greater than second string.\n");
    }

    return 0;
}

Example Output Using strcmp()

Input:
Enter first string: Apple
Enter second string: Banana

Output:
First string is smaller than second string.

2. Method 2: Manual Comparison Using Pointers

In this method, you compare two strings manually by using pointers to traverse each character of the strings. You check each character pair and stop when a difference is found or the end of a string is reached.

This method avoids using `strcmp()` and helps understand the low-level workings of string comparison in C.

Algorithm Using Pointers

Step 1: Start the program.

Step 2: Include `stdio.h` for input/output functions.

Step 3: Declare two character arrays and two pointer variables to point to the arrays.

Step 4: Input both strings from the user.

Step 5: Initialize pointers to point to the first character of each string.

Step 6: Traverse both strings simultaneously using the pointers.

Step 7: Compare the characters pointed by the pointers. If they differ, break the loop.

Step 8: After traversal, determine the relationship:

- If both pointers reach '\0' → strings are equal.

- If first pointer character < second pointer character → first string is smaller.

- If first pointer character > second pointer character → first string is greater.

Step 9: Print the result.

Step 10: End the program.

C Program Using Pointers

C
Compare two strings manually using pointers
#include <stdio.h>
#include <string.h>

int main() {
    char str1[100], str2[100];
    char *p1, *p2;

    printf("Enter first string: ");
    fgets(str1, sizeof(str1), stdin);
    if(str1[strlen(str1)-1] == '\n') str1[strlen(str1)-1] = '\0';

    printf("Enter second string: ");
    fgets(str2, sizeof(str2), stdin);
    if(str2[strlen(str2)-1] == '\n') str2[strlen(str2)-1] = '\0';

    p1 = str1;
    p2 = str2;

    while(*p1 != '\0' && *p2 != '\0') {
        if(*p1 != *p2) break;
        p1++;
        p2++;
    }

    if(*p1 == '\0' && *p2 == '\0') {
        printf("Both strings are equal.\n");
    } else if(*p1 < *p2) {
        printf("First string is smaller than second string.\n");
    } else {
        printf("First string is greater than second string.\n");
    }

    return 0;
}

Example Output Using Pointers

Input:
Enter first string: Mango
Enter second string: Apple

Output:
First string is greater than second string.

Notes and Best Practices

- The `strcmp()` function is faster and simpler for most cases, as it is optimized internally.

- Manual comparison using pointers is useful for learning pointer arithmetic and string internals.

- Using `gets()` is unsafe because it can cause buffer overflow. Prefer `fgets(str, sizeof(str), stdin)` for safety.

- Strings are compared lexicographically based on ASCII values. Uppercase letters have lower ASCII values than lowercase letters.

- Comparing strings manually allows more control, such as ignoring case or skipping whitespace if required.

- Always ensure strings are null-terminated before comparison to avoid undefined behavior.

Conclusion

Comparing strings in C is a fundamental skill for working with textual data. Using `strcmp()` is convenient for most programs, but manual comparison using pointers provides deeper insight into string handling and memory in C.

By practicing both methods, you gain flexibility in handling strings safely and efficiently. Understanding pointers, arrays, and null-terminated strings is essential for effective C programming.