C++中string::compare的使用详解
发布时间:2021-12-05 12:54:33 所属栏目:教程 来源:互联网
导读:在C++中使用std::string编写字符串相关操作时,我经常使用find方法,其实在有些场景下需要判断字符串是否相同,因而需要使用compare方法。下面是我的测试样例: //description: 演示String::compare函数的用法,比较两个字符串是否相等? //compile: g++ -g c
在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; } linuxidc@linuxidc:~/www.linuxidc.com/Linux公社 -$ g++ www.linuxidc.com.c -o linuxidc.com linuxidc@linuxidc:~/www.linuxidc.com/Linux公社 -$ ./linuxidc.com apple is an apple! green apple is not red apple still, green apple is an apple! and red apple is also an apple! therefore, both are apples! ![]() (编辑:牡丹江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐