What is the method of comparing the size of strings in C++?
In C++, you can use comparison operators (<, >, <=, >=) to compare the size of two string objects. Essentially, when comparing two string objects, you are comparing them based on their lexicographical order (i.e. comparing them in alphabetical order). For example:
#include <iostream>
#include <string>
int main() {
std::string str1 = "abc";
std::string str2 = "def";
if (str1 < str2) {
std::cout << "str1 is less than str2" << std::endl;
} else if (str1 > str2) {
std::cout << "str1 is greater than str2" << std::endl;
} else {
std::cout << "str1 is equal to str2" << std::endl;
}
return 0;
}
In the code above, two string objects str1 and str2 are first defined, and then the comparison operator is used to compare their sizes. According to the lexicographical order rule, “abc” is less than “def”, hence the output result is “str1 is less than str2”.
More tutorials
How is the string format used in C++?(Opens in a new browser tab)
2D array for C++ implementation(Opens in a new browser tab)
What is the purpose of resize in C++?(Opens in a new browser tab)
Converting a C++ string to uppercase and lowercase.(Opens in a new browser tab)
Convert string to XML document in Java(Opens in a new browser tab)