×

C program to compare the two strings

C program to compare the two strings

Strings can be compared either by using the string function or without using string function. First, we will look at how we can compare the strings with the help of string function, i.e., strcmp(), which is defined in a string.h header file.

String comparison by using string function

The string function which is pre-defined in a string.h header file is a strcmp() function. The strcmp() function consider two strings as a parameter, and this function returns an integer value where the integer value can be zero, positive or negative.

The syntax of the strcmp() function is given below:

int strcmp (const char* str1, const char* str2);

In the above syntax, two parameters are passed as strings, i.e., str1 and str2, and the return type is int means that the strcmp() returns an integer value.

The strcmp() function compares the character of both the strings. If the first character of both the strings are same, then this process of comparison will continue until all the characters are compared or the pointer points to the null character ‘\0’.

Possible return values from the strcmp() function

Return value Description
0 When both the strings are equal.
<0 If the ASCII value of a character of the first string is less than the ASCII value of a character of the second string, then the function will return negative value.
>0 If the ASCII value of a character of the first string is greater than the ASCII value of a character of the second string, then the function will return positive value.

Let’s understand through an example.

#include <stdio.h>

#include<string.h>

int main()

{

   char str1[20];  // declaration of char array

   char str2[20];  // declaration of char array

   int value; // declaration of integer variable

   printf("Enter the first string : ");

   scanf("%s",str1);

   printf("Enter the second string : ");

   scanf("%s",str2);

   // comparing both the strings using strcmp() function

   value=strcmp(str1,str2);

   if(value==0)

   printf("strings are same");

   else

   printf("strings are not same");

   return 0;

}

Analysis of the above program

  • We have declared two arrays of char type, i.e., str1 and str2. We take the user input as strings.
  • We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.

Output

String comparison without using strcmp() function

#include <stdio.h>

int compare(char[],char[]);

int main()

{

   char str1[20]; // declaration of char array

   char str2[20]; // declaration of char array

   printf("Enter the first string : ");

   scanf("%s",str1);

   printf("Enter the second string : ");

   scanf("%s",str2);

   int c= compare(str1,str2); // calling compare() function

   if(c==0)

   printf("strings are same");

   else

   printf("strings are not same");

    return 0;

}

// Comparing both the strings.

int compare(char a[],char b[])

{

    int flag=0,i=0;  // integer variables declaration

    while(a[i]!='\0' &&b[i]!='\0')  // while loop

    {

       if(a[i]!=b[i])

       {

           flag=1;

           break;

       }

       i++;

    }

    if(flag==0)

    return 0;

    else

    return 1;

}

Analysis of the above program

  • In the above, we have declared two arrays of char type, and we take the user input as strings.
  • We have defined a compare() function which will take user input strings as a parameter, and compare both the strings. If the function returns 0, which means that both the strings are equal otherwise both the strings are not equal.

Output

String comparison by using pointers

#include <stdio.h>

int stringcompare(char*,char*);

int main()

{

  char str1[20]; // declaration of char array

  char str2[20]; // declaration of char array

  printf("Enter the first string : ");

  scanf("%s",str1);

  printf("\nEnter the second string : ");

  scanf("%s",str2);

  int compare=stringcompare(str1,str2); // calling stringcompare() function.

  if(compare==0)

  printf("strings are equal");

 else

 printf("strings are not equal");

return 0;

}

// Comparing both the strings using pointers

int stringcompare(char *a,char *b)

{

   int flag=0;

    while(*a!='\0' && *b!='\0')  // while loop

    {

        if(*a!=*b)

        {

            flag=1;

        }

        a++;

        b++;

    }

    if(flag==0)

    return 0;

    else

    return 1;

}

Analysis of the above program

  • We have created two arrays of char type str1 and str2. We take the user input as strings.
  • We have defined a stringcompare() function which will take two pointers of char type as a parameter. The ‘a’ pointer holds the address of str1 and ‘b’ pointer holds the address of str2. Inside the function, we have created a while loop which will execute until the pointer a or b is not reached to a null character.

Output


Related Topics

How to initialize array to zero in C

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

File Operations in C

Why do I need the file? All data will be lost when the program exits. Saving data to a file keeps it safe even if the program stops working. If there...

6 minutes read.

Flexible Array Members in a Structure in C

There is flexibility to declare array from c99 generation onwards that declaration of the collections can be made possible without even mentioning its dimension, which means that the displays are...

4 minutes read.

C and C++ Binary Files

What is a binary file? A file in which the content is written in binary format is called a binary file. A binary file is not a text file. There are...

7 minutes read.

Stdio.h in C

Header files are used to make the programmer’s efforts a lot easier. In order to make the programming simple, there are a number of libraries which are included as predefined...

4 minutes read.

Factorial Program in C Using While Loop

Before looking into the mechanism of factorial program, first, you have to understand about the working of a while loop. While Loop The syntax that has been used for the “while” loop...

4 minutes read.

Matrix Multiplication in C

Matrix Multiplication in C Matrix multiplication in C: Two matrices can be added, subtracted, multiplied, and divided. To do so, we take input from the consumer for row number, column number, first element matrix,...

3 minutes read.

C Program to find the Roots of a Quadratic Equation

What is Quadratic Equation: Equations of degree 2 in polynomial form are called quadratic equations. A, B, and C are the coefficient variables in the equation, which is written as ax2...

3 minutes read.

Ftell() Function in C

Ftell(): In File Handling we have some special functions like Ftell(), Fseek(), rewind() etc.. while you are randomly accessing the file these functions play very important role and these functions...

3 minutes read.

Difference between Array and List in C

C# Array vs List is where the abstraction and implementation of human computing meet.  Arrays are incredibly related to the hardware concept of contiguous and contiguous memory, where each part is...

3 minutes read.

Isalnum() function in C

Introduction: The isalnum () is a function used in C programming language. This function checks the passing number or argument is an alphanumeric number or not. The alphanumeric number consists of the...

3 minutes read.

Storage Class in C

C storage class is used to define the scope variables and function. There are four various types of storage classes that are given below. auto: The auto keyword is the default...

1 minute read.

Local Labels in C

Anyone who has written programs in the C programming language is required to be familiar with the "go to" and "labels" used in C to navigate between functions. "Local labels"...

4 minutes read.

Variable Declaration in C

What is a Variable? A Variable is nothing more than a name for a memory place where data/information can be stored. Any alphabet (from a to z or A to Z), the...

4 minutes read.

Segmentation Fault in C

Segmentation Fault in C In the C programming language, segmentation fault or segmentation violation or core dump is a condition that the hardware component raises to protect the memory by indicating...

4 minutes read.

Use of Structure in C

We can usually use arrays in C programming to store elements of the same data type. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

C String Manipulation programs without using Library Functions

C string manipulation programs without using Library Functions The string is the character list, and typically we operate with library functions to read and print the entire string, but here you...

6 minutes read.

gets() function in C

gets() is a pre-define or built-in function present in the stdio.h header file. stdio stands for standard input and output. gets() function is used to read a stream and store...

4 minutes read.

OpenGL in C

OpenGL stands for Open Graphics Library. It is a low-level, widely supported modeling and rendering software package that is widely available across all the platforms. It is an API used...

4 minutes read.

Difference between rand() and srand() function in C

What is the rand()? The rand() means random function. This function is used in C. It generates random numbers in the range of 0 to the RAND_MAX. Suppose we generate a...

3 minutes read.