int compare (const basic_string& s) const;
int compare (const Ch* p) const;
int compare (size_type pos, size_type n, const basic_string& s) const;
int compare (size_type pos, size_type n, const basic_string& s,size_type pos2, size_type n2) const;
int compare (size_type pos, size_type n, const Ch* p, size_type = npos) const;
s.compare {pos,n, s2);
若參與比較的兩個串值相同,則函數返回 0;若字串 S 按字典順序要先於 S2,則返回負值;反之,則返回正值。下面舉例說明如何使用 string 類的 compare() 函數。#include <iostream> #include <string> using namespace std; int main () { string A ("aBcdef"); string B ("AbcdEf"); string C ("123456"); string D ("123dfg"); //下面是各種比較方法 int m=A.compare (B); //完整的A和B的比較 int n=A.compare(1,5,B,4,2); //"Bcdef"和"AbcdEf"比較 int p=A.compare(1,5,B,4,2); //"Bcdef"和"Ef"比較 int q=C.compare(0,3,D,0,3); //"123"和"123"比較 cout << "m = " << m << ", n = " << n <<", p = " << p << ", q = " << q << endl; cin.get(); return 0; }程式的執行結果為:
m = 1, n = -1, p = -1, q = 0
由此可知,string 類的比較 compare() 函數使用非常方便,而且能區分字母的大小寫。建議讀者多使用此函數。#include <iostream> #include <string> using namespace std; void TrueOrFalse (int x) { cout << (x?"True":"False")<<endl; } int main () { string S1 = "DEF"; string CP1 = "ABC"; string CP2 = "DEF"; string CP3 = "DEFG"; string CP4 ="def"; cout << "S1= " << S1 << endl; cout << "CP1 = " << CP1 <<endl; cout << "CP2 = " << CP2 <<endl; cout << "CP3 = " << CP3 <<endl; cout << "CP4 = " << CP4 <<endl; cout << "S1 <= CP1 returned "; TrueOrFalse (S1 <=CP1); cout << "S1 <= CP2 returned "; TrueOrFalse (S1 <= CP2); cout << "S1 <= CP3 returned "; TrueOrFalse (S1 <= CP3); cout << "CP1 <= S1 returned "; TrueOrFalse (CP1 <= S1); cout << "CP2 <= S1 returned "; TrueOrFalse (CP2 <= S1); cout << "CP4 <= S1 returned "; TrueOrFalse (CP4 <= S1); cin.get(); return 0; }程式執行結果為:
S1= DEF
CP1 = ABC
CP2 = DEF
CP3 = DEFG
CP4 = def
S1 <= CP1 returned False
S1 <= CP2 returned True
S1 <= CP3 returned True
CP1 <= S1 returned True
CP2 <= S1 returned True
CP4 <= S1 returned False
NULL
,否則程式會異常退出。