用 std::string 處理字串時,我平常最常用 find;但有些場景真正要判斷的是「兩段字串是否相同」,這時就該用 compare。compare 的方便之處在於它不要求兩段字串等長,還能指定起始位置與長度做局部比對。
compare 傳回 0 代表相等,大於 0 或小於 0 則代表字典序上的先後關係。因此判等時寫 == 0,而不是直接用 bool。
//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;
// 從位置 6 起取 5 個字元與 "apple" 比較
if(str1.compare(6, 5, "apple") == 0)
cout << "still, " << str1 << " is an apple!" << endl;
// 從倒數第 5 個字元開始取 5 個字元
if(str2.compare(str2.size() - 5, 5, "apple") == 0)
cout << "and " << str2 << " is also an apple!" << endl;
// 與另一個 string 的指定區段比較
if(str1.compare(6, 5, str2, 4, 5) == 0)
cout << "therefore, both are apples!" << endl;
return 0;
}· compare(const string&):與整個字串比。
· compare(pos, len, const char*):取自身子字串比。
· compare(pos1, len1, str, pos2, len2):兩邊都取子字串比。
這幾個重載讓「比對某段內容」變得非常直接,不必先 substr 再比,省下一份記憶體配置。