C Program To Compare Two Strings

7 min read

c program to compare two strings

A c program to compare two strings is one of the most fundamental exercises for anyone learning the C programming language. Also, string manipulation is a core skill because it appears in real-world applications like text processing, data validation, and even in system-level programming. Whether you are a beginner or revisiting C after some time, understanding how to compare strings correctly will deepen your grasp of memory management, character arrays, and built-in library functions. This guide walks you through the logic, the code, and the reasoning behind each step so you can write a reliable program from scratch Small thing, real impact..

Understanding String Comparison in C

In C, a string is not a built-in data type like it is in languages such as Python or Java. Instead, a string is represented as a null-terminated character array. The null character '\0' marks the end of the string. This means when you compare two strings, you are not comparing two objects directly; you are comparing the sequence of characters until the null terminator is reached.

Two strings are considered equal when every corresponding character matches, including the length. Practically speaking, if one string is longer than the other, they are not equal even if the shorter string matches the beginning of the longer one. As an example, "apple" and "apple " are different because the second string has an extra space and a null terminator at a different position Easy to understand, harder to ignore..

The C standard library provides the strcmp() function in <string.h> for this purpose, but writing your own comparison logic is an excellent exercise in loops, arrays, and character handling It's one of those things that adds up..

Step-by-Step Guide to Write a C Program to Compare Two Strings

Below is a complete, beginner-friendly approach to writing a c program to compare two strings without relying on strcmp(). Each step explains what the code does and why it matters.

Step 1: Include Necessary Headers

Start by including the required header files. <stdio.Consider this: h> gives you input/output functions like printf() and scanf(), while <string. h> provides string-related functions if you choose to use them later.

#include 

If you plan to use strcmp() for verification, you can also include <string.h>.

Step 2: Define the Main Function

Every C program begins with main(). This is the entry point where your code executes.

int main() {

Step 3: Declare Variables and Arrays

You need two character arrays to hold the strings entered by the user. A common size like 100 characters is sufficient for demonstration purposes.

    char str1[100], str2[100];

You can also declare an integer variable to store the result of the comparison Worth knowing..

Step 4: Input Two Strings from the User

Use scanf() or gets() (though gets() is deprecated) to read input. With scanf(), remember to use %s for strings, but note that it stops at the first whitespace. For strings with spaces, you might use fgets().

    printf("Enter first string: ");
    scanf("%99s", str1);
    printf("Enter second string: ");
    scanf("%99s", str2);

The %99s limits input to 99 characters plus the null terminator, preventing buffer overflow.

Step 5: Implement the Comparison Logic

This is the core of the c program to compare two strings. You will iterate through both arrays simultaneously, comparing each character.

    int i = 0;
    while (str1[i] != '\0' && str2[i] != '\0') {
        if (str1[i] != str2[i]) {
            break;
        }
        i++;
    }

After the loop, you check three conditions:

  1. If both characters at position i are null, the strings are identical.
  2. If the characters differ, the strings are not equal.
  3. If one string ends before the other, they have different lengths.

Here is the full conditional block:

    if (str1[i] == '\0' && str2[i] == '\0') {
        printf("Both strings are equal.\n");
    } else if (str1[i] < str2[i]) {
        printf("First string is smaller.\n");
    } else {
        printf("Second string is smaller.\n");
    }

The terms "smaller" and "larger" refer to lexicographical order, similar to dictionary ordering, based on the ASCII values of the characters Practical, not theoretical..

Step 6: Display the Result

The printf() statements above already output the result. You can also display which string is lexicographically smaller or larger by comparing the first differing character.

Scientific Explanation Behind String Comparison

At the machine level, a string is stored in memory as a sequence of bytes representing ASCII or Unicode characters. Also, when you compare two strings in C, the program reads each byte sequentially until it finds a mismatch or reaches the null terminator. This process is essentially a linear scan, making the time complexity O(n), where n is the length of the shorter string.

The lexicographical comparison uses the numeric value of each character. To give you an idea, the ASCII value of 'A' is 65, while 'a' is 97. This means uppercase and lowercase letters are treated differently, so "Apple" and "apple" are not equal in a case-sensitive comparison.

If you need a case-insensitive comparison, you can convert both strings to the same case using tolower() or toupper() before comparing, or use strcasecmp() if available on your platform.

Common Mistakes to Avoid

When writing a c program to compare two strings, beginners often encounter these pitfalls:

  • Using == to compare strings: In C, == compares the memory addresses of the arrays, not the contents. Always use a loop or strcmp().
  • Ignoring the null terminator: Forgetting to check for '\0' can lead to reading beyond the string boundary and undefined behavior.
  • Not limiting input size: Failing to restrict scanf() input can cause buffer overflow, which is a serious security risk.
  • Misunderstanding lexicographical order: Remember that comparison is based on ASCII values, so symbols and numbers come before letters.

FAQ

Can I use strcmp() instead of writing my own logic?
Yes, strcmp() is part of the C standard library and handles all edge cases. Even so, writing your own logic is a valuable learning exercise.

What is the difference between strcmp() and strncmp()?
strcmp() compares the entire strings until a mismatch or null terminator. strncmp() compares only the first n characters, which is useful when you only need a partial comparison.

How do I compare strings without regard to case?
Use strcasecmp() if your compiler supports it, or convert both strings to lowercase/uppercase before comparing Which is the point..

What happens if one string is a prefix of the other?
If one string is shorter but identical to the start of the longer string (e.g., "cat" and "category"), the comparison ends when the null terminator of the shorter string is reached. In this case, the shorter string is considered lexicographically smaller The details matter here..

Practical Applications of String Comparison

String comparison is not just a classroom exercise; it is a fundamental building block for many real-world software functions:

  1. Sorting Algorithms: Whether it is an alphabetical list of contacts or a sorted file directory, algorithms like QuickSort or MergeSort rely on string comparison to determine the order of elements.
  2. Authentication Systems: When you enter a password, the system compares the hash of your input string against the stored hash to grant access.
  3. Search Engines: Basic search functionality often involves comparing a query string against a database of keywords to find exact or partial matches.
  4. Compiler Design: Lexical analyzers compare source code tokens against a set of reserved keywords (like if, while, or return) to determine the structure of the program.

Summary Table: Manual Comparison vs. strcmp()

Feature Manual Loop Comparison strcmp() Function
Implementation Custom logic using while or for Standard library <string.h>
Control Full control over comparison logic Fixed standard behavior
Efficiency Depends on implementation Highly optimized by compiler
Complexity O(n) O(n)
Best Use Case Learning and custom rules Production-ready code

Conclusion

Comparing two strings in C provides a foundational understanding of how data is stored and manipulated in memory. While the standard library offers the strcmp() function for efficiency and reliability, implementing the logic manually reveals the importance of the null terminator and the underlying ASCII numeric system. Consider this: by avoiding common pitfalls—such as using the == operator for content comparison—and understanding the linear time complexity of the process, developers can write more dependable and secure C programs. Whether you are building a simple sorting tool or a complex data parser, mastering string comparison is an essential step in becoming a proficient C programmer.

Just Made It Online

Just Came Out

Close to Home

Stay a Little Longer

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