在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++中比較字符串的一些常用方法,開發者可以根據自己的需求選擇合適的方法來比較字符串。