std::basic_string<CharT,Traits,Allocator>:: find
|
size_type find
(
const
basic_string
&
str, size_type pos
=
0
)
const
;
|
(1) |
(C++11 起为 noexcept)
(C++20 起为 constexpr) |
|
size_type find
(
const
CharT
*
s, size_type pos, size_type count
)
const
;
|
(2) | (C++20 起为 constexpr) |
|
size_type find
(
const
CharT
*
s, size_type pos
=
0
)
const
;
|
(3) | (C++20 起为 constexpr) |
|
size_type find
(
CharT ch, size_type pos
=
0
)
const
;
|
(4) |
(C++11 起为 noexcept)
(C++20 起为 constexpr) |
|
template
<
class
StringViewLike
>
size_type find
(
const
StringViewLike
&
t,
|
(5) |
(C++17 起)
(C++20 起为 constexpr) |
查找首个与给定字符序列相等的子串。搜索从 pos 开始,即找到的子串起始位置不得早于 pos 。
[
s
,
s
+
count
)
相等的子串。该范围可能包含空字符。
std:: basic_string_view < CharT, Traits >> 为 true 且 std:: is_convertible_v < const StringViewLike & , const CharT * > 为 false 时参与重载决议。
形式上,当满足以下所有条件时,称子串 str 在位置 xpos 被 找到 :
- xpos >= pos
- xpos + str. size ( ) <= size ( )
- 对于 str 中的所有位置 n ,满足 Traits :: eq ( at ( xpos + n ) , str. at ( n ) ) 。
具体而言,这意味着
- 仅当 pos <= size ( ) - str. size ( ) 时才能找到子串
- 当且仅当 pos <= size ( ) 时,可以在该位置找到空子串
- 对于非空子串,若 pos >= size ( ) ,函数始终返回 npos
目录 |
参数
| str | - | 要搜索的字符串 |
| pos | - | 开始搜索的位置 |
| count | - | 要搜索的子串长度 |
| s | - | 指向要搜索的字符串的指针 |
| ch | - | 要搜索的字符 |
| t | - | 要搜索的对象(可转换为 std::basic_string_view ) |
返回值
找到的子串首字符位置,若未找到该子串则返回 npos 。
异常
若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。
示例
#include <iomanip> #include <iostream> #include <string> void print(int id, std::string::size_type n, std::string const& s) { std::cout << id << ") "; if (std::string::npos == n) std::cout << "not found! n == npos\n"; else std::cout << "found @ n = " << n << ", substr(" << n << ") = " << std::quoted(s.substr(n)) << '\n'; } int main() { std::string::size_type n; std::string const s = "This is a string"; /* ^ ^ ^ 1 2 3 */ // 从字符串开头开始搜索 n = s.find("is"); print(1, n, s); // 从位置5开始搜索 n = s.find("is", 5); print(2, n, s); // 查找单个字符 n = s.find('a'); print(3, n, s); // 查找单个字符 n = s.find('q'); print(4, n, s); }
输出:
1) found @ n = 2, substr(2) = "is is a string" 2) found @ n = 5, substr(5) = "is a string" 3) found @ n = 8, substr(8) = "a string" 4) not found! n == npos
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 适用标准 | 发布时的行为 | 修正后的行为 |
|---|---|---|---|
| LWG 847 | C++98 | 未提供异常安全保证 | 增加强异常安全保证 |
| LWG 2064 | C++11 | 重载版本 (3,4) 带有 noexcept 修饰符 | 已移除 |
| LWG 2946 | C++17 | 重载版本 (5) 在某些情况下会导致歧义 | 通过模板化避免歧义 |
| P1148R0 |
C++11
C++17 |
重载版本
(4,5)
的 noexcept 修饰符
因 LWG2064/LWG2946 被意外丢弃 |
已恢复 |
参见
|
查找字符子串的首次出现
(函数) |
|
|
在宽字符串中查找另一个宽字符串的首次出现
(函数) |
|
|
查找字符的首次出现
(函数) |
|
|
在宽字符串中查找宽字符的首次出现
(函数) |
|
|
查找子串的最后一次出现
(公开成员函数) |
|
|
查找字符的首次出现
(公开成员函数) |
|
|
查找字符的首次缺失
(公开成员函数) |
|
|
查找字符的最后一次出现
(公开成员函数) |
|
|
查找字符的最后一次缺失
(公开成员函数) |
|
|
在视图中查找字符
(
std::basic_string_view<CharT,Traits>
的公开成员函数)
|
|
|
搜索元素范围的首次出现
(函数模板) |