std::basic_string<CharT,Traits,Allocator>:: find_first_not_of
|
size_type find_first_not_of
(
const
basic_string
&
str,
size_type pos = 0 ) const ; |
(1) |
(自 C++11 起为 noexcept)
(自 C++20 起为 constexpr) |
|
size_type find_first_not_of
(
const
CharT
*
s,
size_type pos, size_type count ) const ; |
(2) | (自 C++20 起为 constexpr) |
|
size_type find_first_not_of
(
const
CharT
*
s,
size_type pos = 0 ) const ; |
(3) | (自 C++20 起为 constexpr) |
|
size_type find_first_not_of
(
CharT ch, size_type pos
=
0
)
const
;
|
(4) |
(自 C++11 起为 noexcept)
(自 C++20 起为 constexpr) |
|
template
<
class
StringViewLike
>
size_type
|
(5) |
(自 C++17 起)
(自 C++20 起为 constexpr) |
查找首个不等于给定字符序列中任意字符的字符。搜索仅考虑区间
[
pos
,
size()
)
。若区间内所有字符均能在给定字符序列中找到,则返回
npos
。
[
s
,
s
+
count
)
中任意字符的字符。该范围可包含空字符。
Traits::length(s)
确定。
std:: basic_string_view < CharT, Traits >> 为 true 且 std:: is_convertible_v < const StringViewLike & , const CharT * > 为 false 时参与重载决议。
在所有情况下,通过调用 Traits::eq 来检查相等性。
目录 |
参数
| str | - | 用于标识要搜索字符的字符串 |
| pos | - | 搜索起始位置 |
| count | - | 标识要搜索字符的字符串长度 |
| s | - | 指向标识要搜索字符的字符串指针 |
| ch | - | 标识要搜索字符的单个字符 |
| t | - | 可转换为 std::basic_string_view 的对象,用于标识要搜索的字符 |
返回值
找到字符的位置,若未找到此类字符则返回 std::string::npos 。
异常
若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。
示例
#include <iostream> #include <string> int main() { // 允许宏名称中包含大写字母、小写字母和数字 const char* pattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789"; std::string data = "1) %FIX, 2) %HACK, and 3) %TODO"; const std::string replacement = "%DONE%"; std::cout << "Before: " << data << '\n'; for (std::string::size_type first{}, last{}; (first = data.find('%', first)) != std::string::npos; first += replacement.size()) { last = data.find_first_not_of(pattern, first + 1); if (last == std::string::npos) last = data.length(); // 此时 first 位于 '%' 处,last 位于找到的子字符串末尾的下一个位置 data.replace(first, last - first, replacement); } std::cout << "After: " << data << '\n'; }
输出:
Before: 1) %FIX, 2) %HACK, and 3) %TODO After: 1) %DONE%, 2) %DONE%, and 3) %DONE%
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的 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>
的公开成员函数)
|