代碼中出現:
if (str.find("abc") != -1) { ... } // 錯誤寫法
標準規定:std::string::find 未找到時返回 std::string::npos,其類型為 size_type(無符號整數),數值通常為 static_cast(即最大值 0xFFFFFFFF...)。
-1 會「不小於 length」?str.length() 返回 size_type(無符號)。-1 是有符號 int。-1 轉為無符號變成巨大的正數(UINT_MAX),遠大於任何字符串長度。if (pos != -1) 恆為 true(因為 npos == (size_t)-1),if (pos < str.length()) 恆為 false。size_t pos = str.find("abc");
if (pos != std::string::npos) { // 找到
// pos 是首次出現位置
}
if (pos == std::string::npos) { // 未找到
}
contains 更直觀if (str.contains("abc")) { ... } // C++20 起支持
npos 比較,別用 -1、0、NULL。find 返回類型是 size_t,別存入 int 截斷。rfind、find_first_of 等同理。