在 C++ 中,可以使用標準庫中的 std::string 類來表示字符串
==:用于檢查兩個字符串是否相等。如果兩個字符串包含相同的字符序列,則它們相等。#include<iostream>
#include<string>
int main() {
std::string str1 = "Hello";
std::string str2 = "Hello";
std::string str3 = "World";
if (str1 == str2) {
std::cout << "str1 and str2 are equal."<< std::endl;
}
if (str1 != str3) {
std::cout << "str1 and str3 are not equal."<< std::endl;
}
return 0;
}
!=:用于檢查兩個字符串是否不相等。如果兩個字符串包含不同的字符序列,則它們不相等。if (str1 != str3) {
std::cout << "str1 and str3 are not equal."<< std::endl;
}
<、>、<=、>=:這些運算符用于按照字典順序(也稱為 lexicographic order)比較字符串。字符串按照字符的 ASCII 值進行比較。#include<iostream>
#include<string>
int main() {
std::string str1 = "apple";
std::string str2 = "banana";
if (str1 < str2) {
std::cout << "str1 is lexicographically less than str2."<< std::endl;
}
if (str1 <= str2) {
std::cout << "str1 is lexicographically less than or equal to str2."<< std::endl;
}
if (str2 > str1) {
std::cout << "str2 is lexicographically greater than str1."<< std::endl;
}
if (str2 >= str1) {
std::cout << "str2 is lexicographically greater than or equal to str1."<< std::endl;
}
return 0;
}
請注意,這些比較運算符的行為與整數和浮點數的比較運算符相似。你可以根據需要使用這些運算符來比較 std::string 類的對象。