阅读量:119
在 C++ 中,可以使用标准库中的 std::string 类来表示字符串
- 相等运算符
==:用于检查两个字符串是否相等。如果两个字符串包含相同的字符序列,则它们相等。
#include
#include
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 class="hljs-keyword">if (str1 != str3) {
std::cout << "str1 and str3 are not equal."<< std class="hljs-keyword">return 0;
}
- 不等运算符
!=:用于检查两个字符串是否不相等。如果两个字符串包含不同的字符序列,则它们不相等。
if (str1 != str3) {
std::cout << "str1 and str3 are not equal."<< std>
- 比较运算符
<、>、<=、>=:这些运算符用于按照字典顺序(也称为 lexicographic order)比较字符串。字符串按照字符的 ASCII 值进行比较。
#include
#include
int main() {
std::string str1 = "apple";
std::string str2 = "banana";
if (str1 < str2 class="hljs-string">"str1 is lexicographically less than str2."<< std class="hljs-keyword">if (str1 <= str2) {
std::cout << "str1 is lexicographically less than or equal to str2."<< std class="hljs-keyword">if (str2 > str1) {
std::cout << "str2 is lexicographically greater than str1."<< std class="hljs-keyword">if (str2 >= str1) {
std::cout << "str2 is lexicographically greater than or equal to str1."<< std class="hljs-keyword">return 0;
}
请注意,这些比较运算符的行为与整数和浮点数的比较运算符相似。你可以根据需要使用这些运算符来比较 std::string 类的对象。