C program to compare two strings character by character

By IncludeHelp Last updated : December 26, 2023

Here, we will learn how to compare two strings character by character in c programming language?

In this program we will read two strings and compare them character by character, we will compare first character of first string with first character of second string, second character of first string with second character of second string and so on until characters are same. If any of the character (first dissimilar character) is not same program will print “Strings are not same” and if all characters are same, program will print “Strings are same”.

Comparing two strings character by character

We will implement this program using two methods:

  1. Using simple method in which we will read strings and compare characters in main() function.
  2. Using user define function in which we will create a function that will take two strings as arguments. Character by character comparison will be done inside the user define function and if they are equal function will return 0 otherwise function will return -1.

C program to compare two strings character by character

/*C - Program to compare two strings 
character by character.*/

#include <stdio.h>

int main()
{
    char str1[] = "Hello";
    char str2[] = "Hello";
    int len1 = 0, len2 = 0;
    int i, isSame = 0;

    //calculate lengths
    i = 0;
    while (str1[i++] != '\0')
        len1++;
    i = 0;
    while (str2[i++] != '\0')
        len2++;

    if (len1 != len2) {
        printf("Strings are not same, lengths are different\n");
        return -1;
    }

    isSame = 1;
    for (i = 0; i < len1; i++) {
        if (str1[i] != str2[i]) {
            isSame = 0;
            break;
        }
    }

    if (isSame)
        printf("Strings are same.\n");
    else
        printf("Strings are not same.\n");

    return 0;
}

Output

Strings are same.

Comparing two strings character by character using user-defined function

#include <stdio.h>

char compareStrings(char s1[], char s2[], int len)
{
    int i = 0;

    for (i = 0; i < len; i++) {
        if (s1[i] != s2[i]) {
            return -1;
        }
    }
    return 0;
}

int main()
{
    char str1[] = "Hello";
    char str2[] = "Hello";
    int len1 = 0, len2 = 0;
    int i;

    //calculate lengths
    i = 0;
    while (str1[i++] != '\0')
        len1++;
    i = 0;
    while (str2[i++] != '\0')
        len2++;

    if (len1 != len2) {
        printf("Strings are not same, lengths are different\n");
        return -1;
    }

    if (compareStrings(str1, str2, len1) == 0)
        printf("Strings are same.\n");
    else
        printf("Strings are not same.\n");

    return 0;
}

Output

Strings are same.

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.