(地基工)std::string::find() 和 std::string::npos
Posted on 2011-04-15 11:59 點(diǎn)點(diǎn)滴滴 閱讀(16113) 評(píng)論(0) 編輯 收藏 引用 所屬分類: 02 編程語言int idx = str.find("abc");
if (idx == string::npos)
...
上述代碼中,idx的類型被定義為int,這是錯(cuò)誤的,即使定義為 unsigned int 也是錯(cuò)的,它必須定義為 string::size_type。
npos 是這樣定義的:
static const size_type npos = -1;
因?yàn)?string::size_type (由字符串配置器 allocator 定義) 描述的是 size,故需為無符號(hào)整數(shù)型別。因?yàn)槿笔∨渲闷饕孕蛣e size_t 作為 size_type,于是 -1 被轉(zhuǎn)換為無符號(hào)整數(shù)型別,npos 也就成了該型別的最大無符號(hào)值。不過實(shí)際數(shù)值還是取決于型別 size_type 的實(shí)際定義。不幸的是這些最大值都不相同。事實(shí)上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是兩者型別大小不同)。因此,比較式 idx == string::npos 中,如果 idx 的值為-1,由于 idx 和字符串string::npos 型別不同,比較結(jié)果可能得到 false。
要想判斷 find() 的結(jié)果是否為npos,最好的辦法是直接比較:
if (str.find("abc") == string::npos) { ... }
錯(cuò)誤:if(str.find("abc") )
注:找不到abc會(huì)返回-1,不為0為True。0為False
if (idx == string::npos)
...
上述代碼中,idx的類型被定義為int,這是錯(cuò)誤的,即使定義為 unsigned int 也是錯(cuò)的,它必須定義為 string::size_type。
npos 是這樣定義的:
static const size_type npos = -1;
因?yàn)?string::size_type (由字符串配置器 allocator 定義) 描述的是 size,故需為無符號(hào)整數(shù)型別。因?yàn)槿笔∨渲闷饕孕蛣e size_t 作為 size_type,于是 -1 被轉(zhuǎn)換為無符號(hào)整數(shù)型別,npos 也就成了該型別的最大無符號(hào)值。不過實(shí)際數(shù)值還是取決于型別 size_type 的實(shí)際定義。不幸的是這些最大值都不相同。事實(shí)上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是兩者型別大小不同)。因此,比較式 idx == string::npos 中,如果 idx 的值為-1,由于 idx 和字符串string::npos 型別不同,比較結(jié)果可能得到 false。
要想判斷 find() 的結(jié)果是否為npos,最好的辦法是直接比較:
if (str.find("abc") == string::npos) { ... }
錯(cuò)誤:if(str.find("abc") )
注:找不到abc會(huì)返回-1,不為0為True。0為False


