以下聲明是什麼意思?string :: npos是什麼意思?
string s="Joe Alan Smith"";
cout << (s.find("Allen") == string::npos) << endl;
以下聲明是什麼意思?string :: npos是什麼意思?
string s="Joe Alan Smith"";
cout << (s.find("Allen") == string::npos) << endl;
http://www.cplusplus.com/reference/string/string/npos/
由於它通常是用於指示故障返回值。
換句話說,如果在給定字符串s
中找不到字符串'Allen',則打印出來。
.find()
方法返回string::npos
如果它未在搜索的字符串中找到目標字符串。它是一個整數,其值不能表示「找到」索引值,通常爲-1。有效的索引值是> = 0的整數,它表示目標字符串被找到的索引。
其實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
的值未被實現定義;該標準指定它是'string :: size_type(-1)'。 – 2011-02-23 20:40:56
@Mike:謝謝。在我的答案中提到了這一點! – Nawaz 2011-02-24 01:27:05