Problem
Given two strings A and B, write a program to string compare in C. Return 0 if both the strings are equal, >0 if the first non-matching character of A has a higher ASCII value than the corresponding character in B, and <0 if the first non-matching character has a smaller ASCII value than the corresponding character in B.
Example
Input
A = “abc”, B = “abc”
Output
0
Explanation
Both the strings are equal. Hence the string compare in C program to compare the two strings returns 0.
Input
A = “abzc”, B = “abcz”
Output
1
Explanation
The first mismatching index is the third index. The corresponding character in A is “z” and in B is “c”. “z” has a greater ASCII value than “c”, hence the string compare in C function returns a number >0.
Solution
There are several ways to string compare in C/C++. First, we will look at comparing two strings by defining our own function. We can iterate over the strings and check if they mismatch at any index. If they mismatch and A[i] > B[i] at that index, it means that the first string is greater than the second, else the second string is greater than the first.
If the strings do not mismatch, we will check if both the strings are of the same size or not. If both the strings are of the same size, the string compare in C will return 0, else if the size of A is greater than B, we will return 1, else -1.
Implementation
#include <bits/stdc++.h>
using namespace std;
// C program to compare the two strings
int compare(string a, string b){
// Iterating over min(len(A), len(B))
for(int i = 0; i < min(a.length(), b.length()); i++){
// A[i]>B[i] means A is lexicographically greater
if (a[i] > b[i]){
return 1;
}
// A[i]<B[i] means B is lexicographically greater
else if (a[i] < b[i]){
return -1;
}
}
/*
If our code reaches here, no character
has been mismatched until now.
Now we will compare two strings by length.
*/
if (a.length() != b.length()){
return (a.size()>b.size());
}
// If lengths are also same, return 0
return 0;
}
// Driver Code
int main(){
string a = "abzc";
string b = "abcz";
cout<<compare(a,b)<<endl;
}
Output
1
Also see : C Static Function, and Tribonacci Series