手机版
你好,游客 登录 注册
背景:
阅读新闻

C++中的string::compare的使用

[日期:2017-02-28] 来源:CSDN  作者:tao_627 [字体: ]

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

//description: 演示String::compare函数的用法,比较两个字符串是否相等?
//compile: g++ -g compare_string.cc -o compare_string
 
#include <string>
#include <iostream>
using namespace std;
 
int main(int argc, char* argv[])
{
    string str1("green apple");
    string str2("red apple");
    string str3("apple");
 
    if(str3.compare("apple") == 0)
        cout << str3 << " is an apple!" << endl;
 
    if(str1.compare(str2) !=0)
        cout << str1 << " is not " << str2 << endl;
 
    if(str1.compare(6, 5, "apple") == 0)
        cout << "still, " << str1 << " is an apple!" << endl;
                                                                                                                                                                       
    if(str2.compare(str2.size() - 5, 5, "apple") == 0)
        cout << "and " << str2 << " is also an apple!" << endl;
 
    if(str1.compare(6, 5, str2, 4, 5) == 0)
        cout << "therefore, both are apples!" << endl;
 
    return 0;
}

运行截图:

C++中的string::compare的使用

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-02/141141.htm

linux
相关资讯       C++  string::compare 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款