String compare in C
How to compare strings in C? You can use do it using strcmp function, without strcmp function and using pointers. Function strcmp is case sensitive and returns 0 if both the strings are same.
C compare strings
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
printf(“Enter a string\n“);
gets(a);
printf(“Enter a string\n“);
gets(b);
if (strcmp(a,b) == 0)
printf(“The strings are equal.\n“);
else
printf(“The strings are not equal.\n“);
return 0;
}
Output of the program:
C string comparison program
We can create a function to compare two strings.
#include <stdio.h>
int compare_strings(char [], char []);
int main()
{
char a[1000], b[1000];
printf(“Input a string\n“);
gets(a);
printf(“Input a string\n“);
gets(b);
if (compare_strings(a, b) == 0)
printf(“Equal strings.\n“);
else
printf(“Unequal strings.\n“);
return 0;
}
int compare_strings(char a[], char b[])
{
int c = 0;
while (a[c] == b[c]) {
if (a[c] == ‘\0‘ || b[c] == ‘\0‘)
break;
c++;
}
if (a[c] == ‘\0‘ && b[c] == ‘\0‘)
return 0;
else
return –1;
}
C string comparison using pointers
We can make a function to check if two strings are similar or not by using character pointers.
#include<stdio.h>
int compare_string(char*, char*);
int main()
{
char first[1000], second[1000]:
int result;
printf(“Input a string\n“);
gets(first);
printf(“Input a string\n“);
gets(second);
result = compare_string(first, second);
if (result == 0)
printf(“The strings are same.\n“);
else
printf(“The strings are different.\n“);
return 0;
}
int compare_string(char *first, char *second) {
while (*first == *second) {
if (*first == ‘\0‘ || *second == ‘\0‘)
break;
first++;
second++;
}
if (*first == ‘\0‘ && *second == ‘\0‘)
return 0;
else
return –1;
}
String comparison is a part of pattern matching e.g. when you press Ctrl+F in a web browser or text editor to search for some text.