Table of Contents
show
strcmp()
Compare two strings
temp_varaible=strcmp(string1,string2);
This function return values that are as follows:
- if Return value < 0 then it indicates str1 is less than str2.
- if Return value > 0 then it indicates str2 is less than str1.
- if Return value = 0 then it indicates str1 is equal to str2.
Program: Comparing two strings using string library function
#include<stdio.h>
#include<string.h>
int main()
{
char s1[100];
char s2[100];
int t;
puts("Enter string 1");
gets(s1);
puts("Enter sting 2");
gets(s2);
t = strcmp(s1,s2);
if(t == 0)
{
printf("Both strings are equal");
}
else
{
printf("Both strings are unequal");
}
return 0;
}
Output
Enter string 1
sjit
Enter sting 2
sjit
Both strings are equal
Program: Comparing two strings without using string library function
#include<stdio.h>
#include<string.h>
int main()
{
char s1[100];
char s2[100];
int i=0,flag=0;
puts("Enter string 1");
gets(s1);
puts("Enter string 2");
gets(s2);
while(s1[i] != '\0' && s2[i] != '\0')
{
if(s1[i] != s2[i])
{
flag = 1;
break;
}
i++;
}
if(flag == 0 && s1[i] == '\0' && s2[i] == '\0')
{
puts("Both strings are equal");
}
else
{
puts("Both strings are unequal");
}
return 0;
}
Output
Enter string 1
sjit
Enter string 2
students
Both strings are unequal
Views: 0