C program to compare two strings is a simple string program that is used to compare two strings using String function in c.

String in c
String in c is a collection of characters. And it ends with the null character.
In c string has different string functions such as strcmp, strrev, strlen, etc.

String compare in c
To compare two strings in c the string class provided one function strcmp() using this function we can compare two strings.
Syntax for strcmp in c :
int len = strcmp(string);
This function returns an integer value.
strcmp returns 0 of both strings are equal
returns -1 if string 1 less than string 2
returns 1 if string 1 greater than string 2

Strcmp example in c :-
int v = strcmp(“technical”,”technical”);
v = 0
Both strings are equal.

Algorithm to compare two strings in c

  1. Declare variable. str1, str2
  2. Take two string input from the user
  3. Compare two strings using string function.
    ret=strcmp(str1,str2)
  4. If ret == 0
    Print both strings are equal
    Else
    Print both strings are not equal

C program to compare two strings

#include<stdio.h>

#include<string.h>

main()

{

char str1[100],str2[100];

printf("Enter a string 1\n");

gets(str1);

printf("Enter a string 2\n");

gets(str2);


if(strcmp(str1,str2)==0)

{

printf("Both strings are equal\n");

}
else

{

printf("Both strings are not equal\n");

}
}

Output :

C program to compare two strings

Write A Comment