C Program to Compare Two Strings Without strcmp()

C Program to Compare Two Strings Without strcmp()

Comparing two strings is one of the most common operations in C programming. Normally, this is done using the standard library function strcmp(), which checks two strings character by character and returns whether they are equal, greater, or smaller.

However, learning to compare strings without strcmp() is very useful. It helps you understand how strings actually work in C, since they are stored as character arrays ending with a null terminator (\0). By writing your own comparison function, you gain deeper insight into how strings are processed in memory.

In this article, we will explore different ways to compare strings manually in C: using loops, using pointers, and using recursion.

Understanding the Problem

To compare two strings, we need to check their characters one by one. If all characters match and both strings end at the same time, the strings are equal. If a mismatch is found, the result depends on the ASCII values of the characters at that position.

For example:

  • "Scorpion" and "Scorpion" → the names are the same
  • "Sub-Zero" and "Kano""Sub-Zero" comes later because 'S' (83) is greater than 'K' (75)
  • "Raiden" and "Liu Kang""Raiden" comes later because 'R' (82) is greater than 'L' (76)

Program 1: Comparing Using a Loop

The simplest approach is to use a loop that checks each character until either a mismatch is found or both strings end.

#include <stdio.h>
#include <string.h>

int main() {

    char str1[100], str2[100];
    int i, flag = 0;

    printf("Enter first string: ");
    fgets(str1, sizeof(str1), stdin);

    printf("Enter second string: ");
    fgets(str2, sizeof(str2), stdin);

    // Remove trailing newline added by fgets (if present)
    str1[strcspn(str1, "\n")] = '\0';
    str2[strcspn(str2, "\n")] = '\0';

    for (i = 0; str1[i] != '\0' || str2[i] != '\0'; i++) {

        if (str1[i] != str2[i]) {

            flag = (str1[i] > str2[i]) ? 1 : -1;
            break;

        }

    }

    if (flag == 0)
        printf("Strings are equal.\n");

    else if (flag > 0)
        printf("First string is greater.\n");

    else
        printf("Second string is greater.\n");

    return 0;

}

This program is clear and directly shows how comparison works.

Program 2: Comparing Using Pointers

Instead of indexes, we can use pointers to move through the strings. This is more elegant and efficient.

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

    printf("Enter second string: ");
    fgets(str2, sizeof(str2), stdin);

    // Remove trailing newline added by fgets (if present)
    str1[strcspn(str1, "\n")] = '\0';
    str2[strcspn(str2, "\n")] = '\0';

    p1 = str1;
    p2 = str2;

    while (*p1 != '\0' && *p2 != '\0' && *p1 == *p2) {

        p1++;
        p2++;

    }

    if (*p1 == '\0' && *p2 == '\0')
        printf("Strings are equal.\n");

    else if (*p1 > *p2)
        printf("First string is greater.\n");

    else
        printf("Second string is greater.\n");

    return 0;

}

This shows the power of pointers for string handling in C.

Program 3: Comparing Using Recursion

We can also use recursion to solve this problem. The function compares the first characters, and if they are equal, it calls itself with the next characters.

#include <stdio.h>
#include <string.h>

int compareStrings(char *s1, char *s2) {

    if (*s1 == '\0' && *s2 == '\0') return 0;
    if (*s1 != *s2) return (*s1 > *s2) ? 1 : -1;

    return compareStrings(s1 + 1, s2 + 1);

}

int main() {

    char str1[100], str2[100];

    printf("Enter first string: ");
    fgets(str1, sizeof(str1), stdin);

    printf("Enter second string: ");
    fgets(str2, sizeof(str2), stdin);

    // Remove trailing newline added by fgets (if present)
    str1[strcspn(str1, "\n")] = '\0';
    str2[strcspn(str2, "\n")] = '\0';

    int result = compareStrings(str1, str2);

    if (result == 0)
        printf("Strings are equal.\n");

    else if (result > 0)
        printf("First string is greater.\n");

    else
        printf("Second string is greater.\n");

    return 0;

}

This approach is elegant, but recursion is not as efficient as loops for long strings.

FAQs on Comparing Strings in C Without strcmp()

1. Why not just use strcmp()?
You absolutely can, and in real projects you should. But writing your own comparison logic helps you understand how C stores and processes strings (as arrays of characters ending with \0).

2. What does it mean when one string is “greater” than another?
It means the comparison is based on the ASCII values of characters. For example, 'b' (98) is greater than 'a' (97). The comparison stops at the first mismatch.

3. What happens if one string is a prefix of another?
The shorter string will be considered “smaller.”
Example: "cat" vs "cater""cat" is smaller because it ends earlier.

4. Which method is the most efficient?

  • The loop method is simple and efficient.
  • The pointer method is just as efficient and often considered more elegant.
  • The recursive method is the least efficient for long strings (due to function calls), but it’s useful for learning.

5. Do I always need to remove \n when using fgets()?
Yes, because fgets() keeps the newline character if there’s space in the buffer. If you don’t remove it, the comparison may give unexpected results.

6. Can I compare strings using == in C?
No. Using == compares the memory addresses of the arrays, not their contents. That’s why you need to compare character by character.

7. What about case sensitivity?
These methods are case-sensitive ("Apple""apple"). If you want case-insensitive comparison, you need to convert both strings to the same case first (e.g., using tolower() or toupper() from <ctype.h>).

8. Which approach should beginners start with?
Start with the loop method, because it is closest to how strcmp() works internally. Once you’re comfortable, experiment with pointers and recursion.

Conclusion

Comparing strings without strcmp() teaches you how strings really work in C. You can use loops, pointers, or recursion to do the job. In practice, the loop and pointer methods are the most common and reliable. Recursion is more of a learning tool than a practical solution.

While real-world code usually uses the standard library, knowing these manual techniques makes you a stronger programmer and prepares you for technical interviews.

References & Additional Resources

A curated collection of textbooks, tutorials, and documentation for learning string comparison and manipulation in C.

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – The classic reference covering strings, arrays, pointers, and essential C programming concepts.
  2. GeeksforGeeks: String Comparison in C – Explains how to compare strings using strcmp(), including examples and best practices in C.
  3. Tutorialspoint: C Strings – Overview of string declaration, initialization, manipulation, and common operations in C.
  4. Cprogramming.com: Strings in C – Guide on string handling, comparisons, and related algorithms in C.
  5. ISO C Standard Library Reference – Official reference for standard C string functions, including strcmp() and other utilities for string manipulation.
Scroll to Top