在C++中比较字符串可以使用以下几种方法:
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
int result = str1.compare(str2);
if (result == 0) {
std::cout << "Two strings are equal" << std::endl;
} else if (result > 0) {
std::cout << "str1 is larger than str2" << std::endl;
} else {
std::cout << "str1 is smaller than str2" << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
if (str1 == str2) {
std::cout << "Two strings are equal" << std::endl;
} else {
std::cout << "Two strings are not equal" << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
if (str1 > str2) {
std::cout << "str1 is larger than str2" << std::endl;
} else {
std::cout << "str1 is smaller than str2" << std::endl;
}
return 0;
}
这些是在C++中比较字符串的一些常用方法,开发者可以根据自己的需求选择合适的方法来比较字符串。