std::basic_string::find
来自cppreference.com
< cpp | string | basic string
| size_type find( const basic_string& str, size_type pos = 0 ) const |
(1) | |
| size_type find( const CharT* s, size_type pos, size_type count ) const; |
(2) | |
| size_type find( const CharT* s, size_type pos = 0 ) const; |
(3) | |
| size_type find( CharT ch, size_type pos = 0 ) const; |
(4) | |
| size_type find( std::basic_string_view<CharT, Traits> sv, size_type pos = 0) const |
(5) | (C++17 起) |
寻找首个等于给定字符序列的子串。搜索始于 pos ,即找到的子串必须不始于 pos 之前的位置。
1) 寻找等于
str 的首个子串。2) 寻找等于
s 所指向的字符数组的首 count 个字符的首个子串。 s 能包含空字符。3) 寻找等于
s 所指向的字符串的首个子串。以首个空字符确定字符串的长度。4) 寻找首个字符
ch (由后述规则当作单字节子串)。5) 寻找等于字符串视图
sv 的首个子串。正式地,若下列全部为 true ,则说在位置 xpos 找到子串 str :
- xpos >= pos
- xpos + str.size() <= size()
- 对于
str中所有位置n, Traits::eq(at(xpos+n), str.at(n))
特别是,这隐含
- 仅若 pos <= size() - str.size() 才能找到子串
- 在
pos找到空子串,若且唯若 pos <= size() - 对于非空子串,若 pos >= size() ,则函数始终返回 npos 。
目录 |
[编辑] 参数
| str | - | 要搜索的 string |
| pos | - | 开始搜索的位置 |
| count | - | 要搜索的子串长度 |
| s | - | 指向要搜索的字符串的指针 |
| ch | - | 要搜索的字符 |
| sv | - | 要搜索的 std::basic_string_view |
[编辑] 返回值
找到的子串的首字符位置,或若找不到这种子串则为 npos 。
[编辑] 异常
|
1-4) (无)
|
(C++11 前) |
|
1,4)
noexcept 规定: noexcept 2,3) (无)
|
(C++11 起) (C++14 前) |
|
1)
noexcept 规定: noexcept 2,3,4) (无)
|
(C++14 起) |
|
5) noexcept 规定:
noexcept |
(C++17 起) |
[编辑] 示例
运行此代码
#include <string> #include <iostream> void print(std::string::size_type n, std::string const &s) { if (n == std::string::npos) { std::cout << "not found\n"; } else { std::cout << "found: " << s.substr(n) << '\n'; } } int main() { std::string::size_type n; std::string const s = "This is a string"; // 从 string 开始搜索 n = s.find("is"); print(n, s); // 从位置 5 开始搜索 n = s.find("is", 5); print(n, s); // 寻找单个字符 n = s.find('a'); print(n, s); // 寻找单个字符 n = s.find('q'); print(n, s); }
输出:
found: is is a string found: is a string found: a string not found
[编辑] 参阅
| 寻找字符子串的首次出现 (函数) | |
| 在另一宽字符串中寻找宽字符串的首次出现 (函数) | |
| 寻找字符的首次出现 (函数) | |
| 寻找宽字符串中宽字符的首次出现 (函数) | |
| 寻找子串的最后一次出现 (公开成员函数) | |
| 寻找字符的首次出现 (公开成员函数) | |
| 寻找字符的首次缺失 (公开成员函数) | |
| 寻找字符的最后一次出现 (公开成员函数) | |
| 寻找字符的最后一次缺失 (公开成员函数) | |
| 查找一个元素区间 (函数模板) |