2011-02-23 109 views

回答

1

.find()方法返回string::npos如果它未在搜索的字符串中找到目標字符串。它是一個整數,其值不能表示「找到」索引值,通常爲-1。有效的索引值是> = 0的整數,它表示目標字符串被找到的索引。

14

其實string::find()返回找到字符串中的位置,但如果沒有找到給定的字符串,它返回string::npos,其中npos意味着沒有位置

npos是無符號整數值,標準將其定義爲-1(有符號表示形式),表示無位置。

//npos is unsigned, that is why cast is needed to make it signed! 
cout << (signed int) string::npos <<endl; 

輸出:

-1

參見在Ideone:http://www.ideone.com/VRHUj

+3

的值未被實現定義;該標準指定它是'string :: size_type(-1)'。 – 2011-02-23 20:40:56

+0

@Mike:謝謝。在我的答案中提到了這一點! – Nawaz 2011-02-24 01:27:05