in java, there is a compareTo method that returns the ascii difference of two strings, and i was wondering if there is a similar method in c++.
Printable View
in java, there is a compareTo method that returns the ascii difference of two strings, and i was wondering if there is a similar method in c++.
Yes there is a similar method in C++.
Maybe what you're looking for is strcmp.
C++ strings can be compared like ints:
C strings can't, and you have to treat them like arrays of characters:Code:string a = "something";
string b = "something else";
if ( a < b ) {
cout << "a is smaller\n";
} else if ( a == b ) {
cout << "a and b are the same\n";
} else {
cout << "b is smaller\n";
}
Or use strcmp from string.h since it does the work for you:Code:int compareTo( char a[], char b[] ) {
for ( int i = 0; a[i] && b[i] && a[i] == b[i]; i++ );
if ( a[i] == '\0' ) {
return -1;
} else if ( b[i] == '\0' ) {
return 1;
} else {
return a[i] - b[i];
}
}
int rc = compareTo( a, b );
if ( rc < 0 ) {
cout << "a is smaller\n";
} else if ( rc == 0 ) {
cout << "a and b are the same\n";
} else {
cout << "b is smaller\n";
}
Code:int rc = strcmp( a, b );
if ( rc < 0 ) {
cout << "a is smaller\n";
} else if ( rc == 0 ) {
cout << "a and b are the same\n";
} else {
cout << "b is smaller\n";
}