Write a program to compare two strings without using string function
#include<stdio.h> int main() { char str1[30], str2[30]; int i; printf("\nEnter two strings :\n"); gets(str1); gets(str2); i = 0; while (str1[i] == str2[i] && str1[i] != '\0') i++; if (str1[i] > str2[i]) printf("str1 > str2 alphabetically"); else if (str1[i] < str2[i]) printf("str1 < str2 alphabetically"); else printf("str1 = str2 alphabetically"); return (0); }
Output
Enter two strings :
nawaraj
shah
str1 < str2 alphabetically
Hey can you please explain the logic behind this while condition
str1[i] == str2[i] && str1[i] != ‘\0’
First of all, it counts from first to last.
For example, if we have two string, lets say str1 = “aserg” and str2 = “asbh”. Here, counting starts from 0 so initially ASCII values of str1[0] and str2[0] being compared means comparing ‘a’ with ‘a’, also str1[0] does not contain ‘\0’. ‘\0’ is used to indicate string end. The while condition is true, so it goes one more loop till srt1[2] and str2[2], where str1[2] = ‘e’ and str2[2] = ‘e’.
Condition fail, loop stop, and ‘i’ have value ‘2’.