string.find(substring)返回substring在string中第一次出現的位置,若是沒有找到則返回std::string::npos。html
#include <iostream> int main() { std::string str("abcabcabcd"); std::cout << str.find("a") << std::endl; std::cout << str.find("bc") << std::endl; std::cout << str.find("za") << std::endl; // 找不到,返回string::npos }
編譯運行:ios
$ g++ -Wall test.cpp $ ./a.out 0 1 18446744073709551615
在一些編程語言中,找不到就返回-1,不過這裏返回了一個很大的數字。web
#include <iostream> int main() { std::string str("abcabcabcd"); std::string::size_type pos1 = str.find("ax"); std::size_t pos2 = str.find("ax"); int pos3 = str.find("ax"); std::cout << pos1 << std::endl; std::cout << pos2 << std::endl; std::cout << pos3 << std::endl; }
編譯運行:編程
$ g++ -Wall test.cpp $ ./a.out 18446744073709551615 18446744073709551615 -1
可見,find()返回的是一個unsigned整數。編程語言
#include <iostream> // #include <string> int main() { std::string str("abcabcabcd"); std::string::size_type position = 0; while((position=str.find("abc",position)) != std::string::npos) { std::cout << "position: " << position << std::endl; position++; } }
編譯運行:code
$ g++ -Wall test.cpp $ ./a.out position: 0 position: 3 position: 6
http://www.cnblogs.com/web100/archive/2012/12/02/cpp-string-find-npos.htmlhtm