有時候經常會判斷一個字符串a中是否有子字符串b,那么有人會調用 string::find這個函數 這個函數返回子字符串首次出現的位置,那么有人會這樣寫
string str1 = ""; if(str1.find("aaaa") >= 0) cout<<"有"<<endl; else cout<<"沒有"<<endl; system("pause"); return 0;
結果輸出是錯誤的。而實際上必須寫成這樣
string str1 = ""; if(str1.find("aaaa") != string::npos) cout<<"有"<<endl; else cout<<"沒有"<<endl;
經過調試發現 find的返回值是無符號整型,也就是說沒有負數。>= 0 在任何時刻都成立的。