Linux 拨号vps windows公众号手机端

c++中string的compare函数有什么用

lewis 9年前 (2017-01-01) 阅读数 10 #程序编程
文章标签 c++

c++中string的compare函数用于比较两个字符串的大小关系。该函数返回一个整数值,表示两个字符串的比较结果。

具体来说,如果字符串相等,则返回0;如果第一个字符串在字典顺序中小于第二个字符串,则返回一个负数;如果第一个字符串在字典顺序中大于第二个字符串,则返回一个正数。

比如:

std::string str1 = "hello";
std::string str2 = "world";

int result = str1.compare(str2);

if(result < 0)
    std::cout << "str1小于str2" << std::endl;
else if(result > 0)
    std::cout << "str1大于str2" << std::endl;
else
    std::cout << "str1等于str2" << std::endl;

这段代码会输出"str1小于str2",因为在字典顺序中,"hello"比"world"小。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门