compare two strings in C
Code snippet on how to compare two strings in C
// Code begins
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "Hello";
char str2[20] = "World";
int compare = strcmp(str1, str2);
if (compare == 0)
printf("Both strings are same");
else
printf("Given strings are different ");
return 0;
}
// Code ends
This code is used to compare two strings. The two strings are “Hello” and “World” and are stored in two char arrays str1 and str2. The strcmp() function is used to compare two strings. It returns 0 if both strings are equal else it returns the difference between their ASCII values. If compare is 0, the strings are equal and “Both strings are same” is printed else “Given strings are different” is printed. Finally the program returns 0.