C program to compare two strings using pointers


Learn how to compare two strings in C using pointers and the strcmp function. This guide provides step-by-step instructions, example code, and explanations for efficient string comparison in C programming.

Comparing two strings is a common task in programming, often used to check if two strings are equal, to sort strings alphabetically, or to find differences between them. In C, strings are arrays of characters, and comparing them using pointers can be an efficient approach. This article will guide you through writing a C program to compare two strings using pointers.

Understanding Pointers and Strings in C

In C, a string is essentially an array of characters ending with a null character (\0). Pointers in C are variables that store memory addresses. Using pointers to manipulate strings can lead to more efficient and readable code.

Steps to Compare Two Strings

  1. Initialize pointers to both strings: Point to the start of each string.
  2. Iterate through each character: Use a loop to compare characters at each position.
  3. Check for equality or difference: Compare characters one by one until a difference is found or the end of both strings is reached.
  4. Handle end conditions: Ensure both strings are fully traversed.

Write a C program to compare two strings using pointers

Here is a simple C program to compare two strings using pointers:

#include <stdio.h>

// Function to compare two strings using pointers
int compareStrings(const char *str1, const char *str2) {
    // Iterate through both strings
    while (*str1 && *str2) {
        // If characters differ, return the difference
        if (*str1 != *str2) {
            return *str1 - *str2;
        }
        // Move to the next character
        str1++;
        str2++;
    }

    // If one string is longer than the other, return the difference
    return *str1 - *str2;
}

int main() {
    // Example strings
    char str1[100], str2[100];

    // Input two strings from the user
    printf("Enter the first string: ");
    gets(str1);
    printf("Enter the second string: ");
    gets(str2);

    // Compare the strings
    int result = compareStrings(str1, str2);

    // Output the result
    if (result < 0) {
        printf("The first string is less than the second string.\n");
    } else if (result > 0) {
        printf("The first string is greater than the second string.\n");
    } else {
        printf("The strings are equal.\n");
    }

    return 0;
}

Output

Enter the first string: ProCoding
Enter the second string: procoding
The first string is less than the second string.

Explanation

  1. Input Handling:
    • The program first reads two strings from the user using gets.
  2. String Comparison Function:
    • The compareStrings function takes two const char * pointers as arguments, pointing to the start of the two strings.
    • The while loop iterates through each character of both strings until the end of either string is reached (str1 && *str2).
    • If the characters at the current positions differ, the difference (str1 - *str2) is returned. This difference is useful for sorting or determining the lexicographical order.
    • If the loop completes without finding a difference, the final difference (str1 - *str2) is returned, which will be zero if both strings are equal, or indicate the longer string if they differ in length.
  3. Output:
    • The main function interprets the result from compareStrings and prints whether the first string is less than, greater than, or equal to the second string.

Write a C program to compare two strings using strcmp()

Certainly! The strcmp function in C is a standard library function used to compare two strings. It is declared in the string.h header file. Using strcmp, you can simplify the string comparison function since strcmp already handles the comparison logic internally.

Here is how you can modify the program to use strcmp:

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

int main() {
    // Example strings
    char str1[100], str2[100];

    // Input two strings from the user
    printf("Enter the first string: ");
    gets(str1);
    printf("Enter the second string: ");
    gets(str2);

    // Compare the strings using strcmp
    int result = strcmp(str1, str2);

    // Output the result
    if (result < 0) {
        printf("The first string is less than the second string.");
    } else if (result > 0) {
        printf("The first string is greater than the second string.");
    } else {
        printf("The strings are equal.");
    }

    return 0;
}

Explanation

  1. Header File:
    • Include string.h for the strcmp function.
  2. Input Handling:
    • The program reads two strings from the user using gets.
  3. String Comparison Using strcmp:
    • strcmp is used to compare the two strings. It returns:
      • A negative value if the first string is less than the second string.
      • Zero if the strings are equal.
      • A positive value if the first string is greater than the second string.
  4. Output:
    • The main function interprets the result from strcmp and prints whether the first string is less than, greater than, or equal to the second string.

Benefits of Using strcmp

  • Simplicity: strcmp abstracts away the detailed comparison logic, making your code cleaner and easier to read.
  • Reliability: strcmp is part of the standard C library, ensuring consistent and well-tested behavior across different platforms and compilers.

By using strcmp, you leverage the power of the standard library to perform string comparisons efficiently and accurately.


Recommended Posts