用std::string::compare比较字符串大小

本文介绍了如何使用C++标准库中的std::string::compare函数来比较两个字符串的大小,并通过示例代码展示了三种重载形式的具体应用。文章还解释了比较结果的含义及其可能的数值范围。

用std::string::compare比较字符串大小

参考见

http://www.cplusplus.com/reference/string/string/compare/

三种常见的重载形式:

int compare (const string& str) const noexcept;
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen) const;

#include <iostream>
#include <string>

int main ()
{
  std::string str1 ("green apple");
  std::string str2 ("red apple");

  if (str1.compare(str2) != 0)
    std::cout << str1 << " is not " << str2 << '\n';

  if (str1.compare(6,5,"apple") == 0)//第一个参数表示str1中的位置:str1[6],第二个参数表示要比较的字符串的最大数量,即从指定位置开始后的比较数目
    std::cout << "still, " << str1 << " is an apple\n";

  if (str2.compare(str2.size()-5,5,"apple") == 0)//同上
    std::cout << "and " << str2 << " is also an apple\n";

  if (str1.compare(6,5,str2,4,5) == 0)//str1中的“apple”和str2中的“apple”比较
    std::cout << "therefore, both are apples\n";

  return 0;
}

output如下:

green apple is not red apple
still, green apple is an apple
and red apple is also an apple
therefore, both are apples

注意:比较的结果不一定为1,0,-1,可能出现+2、-2等情况,当为正数时表示str1大于str2,为零时相等,为负数时小于str2


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值