Does nay one know how to Compare two Strings in C Programming? Say, my program is about to receive a string "DEF", and I want to test if the string really contains "DEF". What is the best way to test it?
Printable View
Does nay one know how to Compare two Strings in C Programming? Say, my program is about to receive a string "DEF", and I want to test if the string really contains "DEF". What is the best way to test it?
Code:#include <stdio.h>
#include <string.h>
int main()
{
char w1[20];
char wd2[20];
printf("\n first character:\n1: ");
scanf("%s", wd1);
printf(" second character:\n 2: ");
scanf("%s", wd2);
if(strcmp(wd1,wd2) == 0)
printf("identical words");
else
printf("%s comes before %s", (strcmp(wd1, wd2) > 0) ? wd2 : wd1, (strcmp(wd1, wd2) < 0) ? wd2 : wd1);
}
With strncmp you only check the first someSaneCharLimit number of characters.strlen() returns the length of a string, excluding the null. If they are the same up to that point they will be equal i.e. strncmp("abcd", "abch", 3) would return a 0 whereas strncmp("abcd", "abch", 4) would return a number greater than 0.
Code:#include<stdio.h>
main()
{
while(st1[i]!='/0' &&st2[i]!='/0')
if(st1[i]!=st2[i])
flag=1;
if(flag==1)
printf("equal");
}