Home > Enterprise >  Can we Compare Two Strings in C Entered by the User
Can we Compare Two Strings in C Entered by the User

Time:04-16

Can we compare two or more strings name entered by the user in c language e.g

#include<stdio.h>
#include<conio.h>
int main()
{
   string x,y;
   printf("Enter first name");
   scanf(%s,&x);
   printf("Enter Second name");
   scanf(%s,&y);
   if(x==y)
     printf("Same Name here")
   else
     printf("Different Names")
}

CodePudding user response:

Yes, you can!!
First, #include <string.h>, and compare string x and y with strcmp(x, y),
strcmp() will return an integer
If strcmp(x, y) == 0, string x equals to string y.
Else string x don't equal to y.

CodePudding user response:

Of Course. Every operation is possible in every language. language doesn't matter, Logic matters a lot. In C lang there is a built-in library for string using which we can do this thing easily.

#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;  
}

Besides this, we can create our own function. If you don't want to use string functions and want to create your own one then, you have to iterate through every character of both strings and need to compare them each time. But it's not recommended. If you Want you can do it for learning purposes, else it's better to use built-in functions.

CodePudding user response:

#include<stdio.h>
#include<conio.h>
#include<string.h>

int main()
{
char* x,y;
printf("Enter first name");
scanf("%s",&x);
printf("Enter Second name");
scanf("%s",&y);
if(strcmp(x, y) == 0)
printf("Same Name here");
else
printf("Different Names");

}

Natively there is no type string in c, only char*

  • Related