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

   2024-10-01 9300
核心提示:在 C++ 中,可以使用标准库中的 std::string 类来表示字符串相等运算符 ==:用于检查两个字符串是否相等。如果两个字符串包含相

在 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 类的对象。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号