1. 程式人生 > >[C++] STL庫函式之字串string::npos的介紹,以及string中的find函式~

[C++] STL庫函式之字串string::npos的介紹,以及string中的find函式~

npos經常和find一起用~它們兩個都在標頭檔案<string>裡面~先看用法:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s = "abc";
    if (s.find("b") != string::npos)
        printf("字串s中存在b字元~");
    else
        printf("字串s中不存在b字元~");
    return 0;
}

簡單點說就是,在字串s中查詢“b”字元(當然也可以查詢一個字串如“ab”),find函式如果找到了,就會返回第一次出現這個字元的位置,如果沒找到怎麼辦呢,它會返回npos這個位置,npos本質上其實是一個常數,一般來說值是-1,所以s.find(“b”) != string::npos表示找到了“b”這個字元~如果相等就是沒找到的意思啦~

我們可以從C++庫函式的官方文件(www.cplusplus.com)中找到對這兩個函式的解釋~

std::string::find——[Return Value] The position of the first character of the first match. If no matches were found, the function returns string::npos.

std::string::npos static const size_t npos = -1; As a return value, it is usually used to indicate no matches.

以及關於為什麼npos的值是-1的解釋:

npos is a static member constant value with the greatest possible value for an element of type size_t. This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.