C program to compare two strings

Write a C program to compare two strings using loop character by character. How to compare two strings without using inbuilt library function strcmp() in C programming. Comparing two strings lexicographically without using string library functions. How to compare two strings using strcmp() library function.

Example

Input

Input string1: Learn at Codeforwin.
Input string2: Learn at Codeforwin.

Output

Both strings are lexographically equal.

Required knowledge

Basic C programming, Loop, String, Functions

Must know -

Logic to compare two strings

Below is the step by step descriptive logic to compare two strings.

  1. Input two strings from user. Store it in some variable say str1 and str2.
  2. Compare two strings character by character till an unmatched character is found or end of any string is reached.
  3. If an unmatched character is found then strings are not equal.
  4. Else if both strings reached their end then both strings are equal.

Program to compare two strings

/**
 * C program to compare two string without using string library functions
 */

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

/* Compare function declaration */
int compare(char * str1, char * str2);


int main()
{
    char str1[MAX_SIZE], str2[MAX_SIZE];
    int res;

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


    /* Call the compare function to compare strings */
    res = compare(str1, str2);

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

    return 0;
}


/**
 * Compares two strings lexicographically. 
 * Returns 0 if both strings are equal, 
 *         negative if first string is smaller
 *         otherwise returns a positive value
 */
int compare(char * str1, char * str2)
{
    int i = 0;

    /* Iterate till both strings are equal */
    while(str1[i] == str2[i])
    {
        if(str1[i] == '\0' && str2[i] == '\0')
            break;

        i++;
    }

    // Return the difference of current characters.
    return str1[i] - str2[i];
}

We can optimize the above while loop in compare function to get little geeky.

  • First let us combine the while and if condition in a single condition.
    while((str1[i] != '\0' && str2[i] != '\0') && (str1[i] == str2[i])) i++;
  • Next we know, in C programming NULL character is represented using 0. Hence, the above NULL checking condition can be stripped out.
    while((str1[i] && str2[i]) && (str1[i] == str2[i])) i++;
  • Further, you can apply pointer arithmetic on above while loop to get more geeky.
    while((*str1 && *str2) && (*str1 == *str2)) { str1++; str2++; }

Let us finally re-write the above program using pointers.

Program to compare two strings using pointers

/**
 * C program to compare two string without using string library functions
 */

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

/* Compare function declaration */
int compare(char * str1, char * str2);


int main()
{
    char str1[MAX_SIZE], str2[MAX_SIZE];
    int res;

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


    /* Call the compare function to compare strings */
    res = compare(str1, str2);

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

    return 0;
}


/**
 * Compares two strings lexicographically. 
 */
int compare(char * str1, char * str2)
{
    while((*str1 && *str2) && (*str1 == *str2)) { str1++; str2++; }

    return *str1 - *str2;
}

We learned to compare two strings manually. However, in series of coding it is always recommended to use predefined library function. You can use strcmp(str1, str2) to compare two strings present in string.h header file. It returns -1 if first string is lexicographically smaller than second string, returns 0 if both string are lexicographically equal else returns 1 if first string is lexicographical greater than second string.

Program to compare strings using strcmp() function

/**
 * C program to compare two string using strcmp() function
 */

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str1[MAX_SIZE], str2[MAX_SIZE];
    int res;

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


    /* Call strcmp() to compare both strings and stores result in res */
    res = strcmp(str1, str2);

    if(res == 0)
    {
        printf("Both strings are equal.");
    }
    else if(res == -1)
    {
        printf("First string is lexicographically smaller than second.");
    }
    else
    {
        printf("First string is lexicographically greater than second.");
    }

    return 0;
}

Output

Enter first string: Learn at CODEFORWIN.
Enter second string: Learn at Codeforwin.
First string is lexicographically smaller than second.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>