Write a C program to compare two strings using loop character by character. How to compare two strings without using inbuilt library function strcmp() in C programming. Comparing two strings lexicographically without using string library functions. How to compare two strings using strcmp() library function.
Example
Input
Input string1: Learn at Codeforwin. Input string2: Learn at Codeforwin.
Output
Both strings are lexographically equal.
Required knowledge
Basic C programming, Loop, String, Functions
Must know –
Logic to compare two strings
Below is the step by step descriptive logic to compare two strings.
- Input two strings from user. Store it in some variable say str1 and str2.
- Compare two strings character by character till an unmatched character is found or end of any string is reached.
- If an unmatched character is found then strings are not equal.
- Else if both strings reached their end then both strings are equal.
Program to compare two strings
We can optimize the above while loop in compare function to get little geeky.
- First let us combine the while and if condition in a single condition.
- Next we know, in C programming NULL character is represented using 0. Hence, the above NULL checking condition can be stripped out.
- Further, you can apply pointer arithmetic on above while loop to get more geeky.
Let us finally re-write the above program using pointers.
Program to compare two strings using pointers
We learned to compare two strings manually. However, in series of coding it is always recommended to use predefined library function. You can use strcmp(str1, str2) to compare two strings present in string.h header file. It returns -1 if first string is lexicographically smaller than second string, returns 0 if both string are lexicographically equal else returns 1 if first string is lexicographical greater than second string.
Program to compare strings using strcmp() function
Output
Enter first string: Learn at CODEFORWIN. Enter second string: Learn at Codeforwin. First string is lexicographically smaller than second.
Happy coding
Recommended posts
- String programming exercises and solution.
- C program to convert uppercase string to lowercase string.
- C program to convert lowercase string to uppercase string
- C program to find reverse of a given string.
- C program to check whether a string is palindrome or not.
- C program to find first occurrence of a character in string.
- C program to remove first occurrence of a character from the string.