Reputation: 67
I want to lexicographically compare two strings of equal length, containing Latin letters. Uppercase and lowercase letters are considered same.
Here is my code:
string in1,in2;
getline(cin,in1);
getline(cin,in2);
int l=in1.length();
for(int i=0;i<l;++i){
in1[i]=tolower(in1[i]);
in2[i]=tolower(in2[i]);
}
int sum1=0;
int sum2=0;
for(int i=0;i<l;++i){
sum1=sum1 + int(in1[i]);
sum2=sum2 + int(in2[i]);
}
if(sum1==sum2)
cout<<"0"<<endl;
if(sum1<sum2)
cout<<"-1"<<endl;
if(sum1>sum2)
cout<<"1"<<endl;
However, this gives errors on certain test conditions.
What is wrong here?
Upvotes: 0
Views: 325
Reputation: 131
You can use compare function
int x = in1.compare(in2);
if(x == 0)
cout<<"Both are Equal";
else if (x > 0)
cout << in1 << " is greater than "<< in2 << endl;
else
cout << in2 << " is greater than "<< in1 << endl;
Upvotes: 1
Reputation: 51864
You can surely use the operators provided by the standard library for std::string
types:
operator==
operator!=
operator< lexicographically compares two strings
operator> (function template)
operator<=
operator>=
For more information, see here.
Upvotes: 1
Reputation: 7152
You can use strcmp
with the std::string
C string extractor c_str()
. Here is a complete working solution that does it:
#include <iostream>
#include <string>
#include <string.h>
int main(int argc, char **argv)
{
std::string s1("aabad");
std::string s2("abaaaaaaa");
if (strcmp(s1.c_str(),s2.c_str()) < 0) std::cout << "s1 < s2\n";
if (strcmp(s1.c_str(),s2.c_str()) > 0) std::cout << "s2 < s1\n";
if (strcmp(s1.c_str(),s2.c_str()) == 0) std::cout << "s1 == s2\n";
return 0;
}
Upvotes: 1
Reputation: 163
I think it wrong because it doesn't consider the order of characters. For example "ab" and "ba" will get the same sum.
Upvotes: 1