断字符串是否相同,使用compare方法

在C++中使用std::string编写字符串相关操作时,我经常使用find方法,其实在有些场景下需要判断字符串是否相同,因而需要使用compare方法。下面是我的测试样例:

[cpp]  view plain  copy
  1. //description: 演示String::compare函数的用法,比较两个字符串是否相等?  
  2. //compile: g++ -g compare_string.cc -o compare_string  
  3.    
  4. #include <string>  
  5. #include <iostream>  
  6. using namespace std;  
  7.    
  8. int main(int argc, char* argv[])  
  9. {  
  10.     string str1("green apple");  
  11.     string str2("red apple");  
  12.     string str3("apple");  
  13.    
  14.     if(str3.compare("apple") == 0)  //字段完全匹配
  15.         cout << str3 << " is an apple!" << endl;  
  16.    
  17.     if(str1.compare(str2) !=0)  
  18.         cout << str1 << " is not " << str2 << endl;  
  19.    
  20.     if(str1.compare(6, 5, "apple") == 0)  
  21.         cout << "still, " << str1 << " is an apple!" << endl;  
  22.                                                                                                                                                                            
  23.     if(str2.compare(str2.size() - 5, 5, "apple") == 0)  
  24.         cout << "and " << str2 << " is also an apple!" << endl;  
  25.    
  26.     if(str1.compare(6, 5, str2, 4, 5) == 0)  
  27.         cout << "therefore, both are apples!" << endl;  
  28.    
  29.     return 0;  
  30. }  
运行截图


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值