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

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

转载于:https://my.oschina.net/letiantian/blog/703802

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值