compare函數用來進行字符串以及其子串的比較,示例如下:
#include <iostream> #include <string> #include <cctype> using std::cout; using std::endl; using std::cin; using std::string; int main(void){ string str1="hi,test,hello"; string str2="hi,test"; //字符串比較 if(str1.compare(str2)>0) printf("str1>str2\n"); else if(str1.compare(str2)<0) printf("str1<str2\n"); else printf("str1==str2\n"); //str1的子串(從索引3開始,包含4個字符)與str2進行比較 if(str1.compare(3,4,str2)==0) printf("str1的指定子串等於str2\n"); else printf("str1的指定子串不等於str2\n"); //str1指定子串與str2的指定子串進行比較 if(str1.compare(3,4,str2,3,4)==0) printf("str1的指定子串等於str2的指定子串\n"); else printf("str1的指定子串不等於str2的指定子串\n"); //str1指定子串與字符串的前n個字符進行比較 if(str1.compare(0,2,"hi,hello",2)==0) printf("str1的指定子串等於指定字符串的前2個字符組成的子串\n"); else printf("str1的指定子串不等於指定字符串的前2個字符組成的子串\n"); return 0; }
執行結果: