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