温馨提示×

如何比较c++ string类的对象

c++
小樊
82
2024-08-28 02:31:57
栏目: 编程语言

在 C++ 中,可以使用标准库中的 std::string 类来表示字符串

  1. 相等运算符 ==:用于检查两个字符串是否相等。如果两个字符串包含相同的字符序列,则它们相等。
#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;
}
  1. 不等运算符 !=:用于检查两个字符串是否不相等。如果两个字符串包含不同的字符序列,则它们不相等。
if (str1 != str3) {
    std::cout << "str1 and str3 are not equal."<< std::endl;
}
  1. 比较运算符 <><=>=:这些运算符用于按照字典顺序(也称为 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 类的对象。

0