×

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

Runtime vs compile time in C

In the C programming language, the often used terms in every step consist of compile time and runtime. The compile time is referred to the source code that will be...

4 minutes read.

How to return a Pointer from a Function in C?

In the C programming language, pointers are variables that hold the address memory location of another variable. We could also input pointers to a function and return pointers from a...

3 minutes read.

Explain the two-way selection in C

In C programming, a two-way selection statement is used to choose between two different options based on a Boolean expression. The two-way selection statement in C is the if statement. The...

6 minutes read.

#undef in C

#undef in C In the C programming language, the #undef directive is used to undefine the macro or any constant, which will be defined by the preprocessor directive #define. The #undef...

3 minutes read.

7 Best IDEs for C/C++ Developers in 2024

As we all know that in programming languages, C is known as the building block which cannot be contradicted, and C++ is the prolong kind of C and it can...

4 minutes read.

What is 2s Complement in C?

The complement of 2s in C is generated from the 1s in C. As we know, the 1s complement of a binary number is generated by converting bit 1 to...

4 minutes read.

Recursion in C

Recursion in C: In the C programming language, the concept known as recursion exists that is a technique in which a function calls itself either directly or indirectly. It allows...

4 minutes read.

Pi() Function in C

Pi: Mathematic constants are not defined in the c or c++ programming languages. To use the Mathematical constants firstly, we have to define the _USE_MATH_DEFINES and then declare the cmath and...

3 minutes read.

C Token

C Token and Keyword The C tokens are the basic buildings blocks in C language which are constructed together to write a C program. Each and every smallest individual unit in the C program is...

2 minutes read.

Comments in C

Comments are used to comment on the line of code in the program. Comments are a way of inserting remarks and reminders into code without affecting its behavior. The compiler...

1 minute read.

Conditional Operator in C

In C programming language, the conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement. The syntax of conditional operator in C is...

3 minutes read.

Compound Interest Program in C

Interest on loans and deposits is compound interest. This is the most commonly used concept in everyday life. Compound interest on an amount is based on principal and interest earned...

3 minutes read.

Bank Account System in C using File Handling

This tells about the creation of bank account system using the C language and handling of files in C. Approach Let us see the approaches and the functions how they are covering...

5 minutes read.

Do WHILE LOOP in C Programming Examples

Before understanding the programming examples of the Do-While loop, we have to know what is Do-While loop in C. So, let's start with the definition of the Do-While loop. What is...

5 minutes read.

Star Program in C Language

Star Program in C Star patterns are a sequence of * or any other character used to construct any pattern or any like-square geometric form, triangle, hollow square, pyramid, rhombus, etc.  Many programmers worldwide highly...

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.

Comma Operator in C

What is a comma operator? The comma operator in the C programming language has the least priority. The comma operator is essentially a binary operator that operates on the first operand...

4 minutes read.

#include in C

In the C programming language, #include is another way of inferring a standard, or a user defines file into the application or program. The preprocessor of the programming standard generally...

4 minutes read.

Types of Function in C

A function is a piece of code that accomplish a certain operation for a specific task. There are two types of functions in C: System-defined function (Library Function)User-defined function 1. System defined Function...

8 minutes read.

Java Array vs ArrayList

As we all know, arrays are linear data structures that allow you to add elements to them continuously in memory address space, whereas ArrayList is a Collection framework class. Despite...

4 minutes read.