×

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 get ASCII value in C

For text data on computers and the internet, ASCII (American Standard Code for Information Interchange). It is the most widely used character encoding standard. One hundred twenty-eight alphabetic, numeric, special...

3 minutes read.

Macros in C

In the C programming language, the macro is defined as a segment of the code replaced by the macro defined value at the beginning. ‘#define’ is the directive that defines...

3 minutes read.

Goto and Labels in C

Introduction Goto in C: The goto statement is known as the jump statement in C. The goto is used to transfer the control of a program to a predefined label. The goto...

3 minutes read.

C/C++ Program to Find the Size of int, float, double and char

In this tutorial, we will learn how to use the sizeof operator to determine the size of each variable. Program to Determine Variable Size Write a C or C++ program to determine the...

2 minutes read.

Exponential() in C

Introduction: In C language, there are available many types of functions. The exponential() function is one of them. It is a mathematical function. This article describes using the pow() property to...

3 minutes read.

Conio.h in C

Header files are the source files with the extension of .h. In c language header files are referred to as the helping files and they contain definitions of various functions...

4 minutes read.

Socket Programming in C

Socket programming is a process that connects the two or more nodes on a networking communication with respective to each other. One of the sockets that determines the socket (I.e.,...

5 minutes read.

How to create a node in C?

A node is a small concept taken from the graph theory, or a node is a fundamental unit of a data structure, like a tree data structure. Every graph contains...

3 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.

Nested Structure in C

In C language, we can create nested Structure (Structure within Structure). There are two ways to define a nested structure. By separate structure By Embedded structure   Separate structure In a separate...

1 minute read.

Entry Control Loop in C

Initially, an entry control loop verifies the termination condition at the entry point. After that, its control passes to the main body of the while or for loop if the...

3 minutes read.

Formatted Input and output function in C

Formatted I/O functions display multiple outputs to the user by taking various inputs. All data types like int, float, char and double are supported by the formatted I/O function. In...

4 minutes read.

Add two numbers using the function in C

Here we will learn how to add two numbers by creating function in C. Let’s learn this with help of example. Code: - #include <stdio.h> int add_two_no(int a, int b); int main(){   int first_num,...

1 minute read.

Commenting in C

Commenting in C Commenting in the C language is used to give out the information about the lines of the code which are included. It is one of the things that...

3 minutes read.

File Handling in C

File Handling is used to open, read, write, search and close file.  C files I/O functions handles data on secondary storage device. File handling function: There are varioushandling functions in C. Function Operation fopen() It is...

4 minutes read.

Array to function in C

Array to function in C We can create functions that receive an array as an argument. To pass an array into a function, we need to write the name of the...

4 minutes read.

Infix to Postfix program in C

Infix Expression: In infix expression, an operator is placed between the two operands. Example: x + y, here operator + is placed between operands x and y. Postfix Expression: In...

3 minutes read.

Function in C

Function is a group of statements that are used to perform any task. In other words, we can say that a function is a self- contained a block of programs...

3 minutes read.

Static in C

Static is a keyword that is used in the C programming language. It can be used both as variables and as functions. In other words, it can be declared both...

3 minutes read.

Simple hash() function in C

Introduction In this context, we briefly discuss HASH FUNCTION, HASHING or HASH TABLE in C. It is a function used to map data and mapped arbitrary sizes to the fixed-size values. The...

7 minutes read.