std::basic_string<CharT,Traits,Allocator>::find_first_not_of
来自 cppreference.cn
< cpp | string | basic string
size_type find_first_not_of( const basic_string& str, size_type pos = 0 ) const; |
(1) | (noexcept since C++11) (constexpr since C++20) |
size_type find_first_not_of( const CharT* s, size_type pos, size_type count ) const; |
(2) | (constexpr since C++20) |
size_type find_first_not_of( const CharT* s, size_type pos = 0 ) const; |
(3) | (constexpr since C++20) |
size_type find_first_not_of( CharT ch, size_type pos = 0 ) const; |
(4) | (noexcept since C++11) (constexpr since C++20) |
template< class StringViewLike > size_type |
(5) | (since C++17) (constexpr since C++20) |
查找等于给定字符序列中任何字符的首个字符。搜索仅考虑范围 [
pos,
size())
。如果给定字符序列中可以找到该范围内的所有字符,将返回 npos。
1) 查找不等于 str 中任何字符的首个字符。
2) 查找不等于范围
[
s,
s + count)
中任何字符的首个字符。此范围可以包含空字符。 如果
[
s,
s + count)
不是有效范围,则行为未定义。3) 查找不等于 s 指向的字符字符串中任何字符的首个字符。字符串的长度由使用
Traits::length(s)
的首个空字符确定。 如果
[
s,
s + Traits::length(s))
不是有效范围,则行为未定义。4) 查找不等于 ch 的首个字符。
仅当
std::is_convertible_v<const StringViewLike&,
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。
[编辑] 异常
1,4) 不抛出任何异常。
5)
noexcept 规范:
noexcept(std::is_nothrow_convertible_v<const T&, std::basic_string_view<CharT, Traits>>)
如果由于任何原因抛出异常,此函数无效(强异常安全保证)。
[编辑] 示例
运行此代码
#include <iostream> #include <string> int main() { // Permit uppercase letters, lowercase letters and numbers in macro names 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(); // Now first at '%' and last is one past end of the found substring 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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
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> 的公共成员函数) |