在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;
}
運行截圖: