c++ string的詳細用法(5)compare()

string a="abcd";
string b="efgh";
string c="1fgh";
string d="fgh";
string e="123efg";

比較兩個字符串的ASCII碼,>0返回1<0返回-1,相同,返回0
ASCII碼比較是字符串的字符從前往後比較,如果之前的比較完成則後面的字符無需比較

1.直接比較兩個字符串
auto number = a.compare(b); //結果爲 number=-1;
auto number = b.compare(a); //結果爲 number=1;
auto number = b.compare(b); //結果爲 number=0;
auto number = a.compare(c); //結果爲 number=1;
auto number = a.compare("abc"); //結果爲 number=1;

2.一個字符串的子串與另一個字符串比較
auto number = b.compare(1,3,d); //結果爲 number=0;
//字符串b從下標爲1的字符開始的三個字符與字符串d比較,顯然都是fgh,所以相等,返回0
auto number = b.compare(1,3,c); //結果爲 number=1;
auto number = b.compare(1,3,"fgh"); //結果爲 number=0;

3.一個字符串的子串與另一個字符串的子串比較
auto number = b.compare(1,3,c,1,3); //結果爲 number= 0;
//字符串b從下標爲1的地方開始的後3個字符是fgh,字符串c從下標爲1的字符開始的後三個字符是fgh,所以相等
auto number = b.compare(0,3,e,3,3); //結果爲 number=0;
//字符串b從下標爲0的地方開始的後3個字符是efg,字符串e從下標爲3的字符開始的後三個字符是efg,所以相等
auto number = b.compare(0,4,"1234efgh",4,4); //結果爲 number=0;
//字符串b從下標爲0的地方開始的後四個字符是efgh,字符串"1234efgh"從下標爲4的字符開始的後4個字符是efgh,所以相等

發佈了20 篇原創文章 · 獲贊 118 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章