温馨提示×

c++中string的compare函数怎么使用

c++
小亿
92
2024-03-01 12:32:14
栏目: 编程语言

在C++中,可以使用string的compare函数来比较两个string对象的大小。该函数的原型如下:

int compare(const string& str) const;

调用该函数时,如果当前string对象小于str,则返回负值;如果当前string对象大于str,则返回正值;如果两个string对象相等,则返回0。

例如:

#include <iostream>
#include <string>

int main() {
    std::string str1 = "hello";
    std::string str2 = "world";

    if (str1.compare(str2) < 0) {
        std::cout << "str1 is less than str2" << std::endl;
    } else if (str1.compare(str2) > 0) {
        std::cout << "str1 is greater than str2" << std::endl;
    } else {
        std::cout << "str1 is equal to str2" << std::endl;
    }

    return 0;
}

运行结果为:

str1 is less than str2

0