C++: string.find()的使用

跟風遠走 提交于 2019-12-09 09:55:40

string.find(substring)返回substring在string中第一次出现的位置,如果没有找到则返回std::string::npos。

示例1

#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
}

编译运行:

$ g++ -Wall test.cpp
$ ./a.out 
0
1
18446744073709551615

在一些编程语言中,找不到就返回-1,不过这里返回了一个很大的数字。

关于string.find()的返回类型

#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++;
    }

}

编译运行:

$ 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.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!