std::basic_string<CharT,Traits,Allocator>::find_last_of
来自 cppreference.cn
< cpp | string | basic_string
size_type find_last_of( const basic_string& str, size_type pos = npos ) const; |
(1) | (C++11 起无异常抛出) (C++20 起为 constexpr) |
size_type find_last_of( const CharT* s, size_type pos, size_type count ) const; |
(2) | (C++20 起为 constexpr) |
size_type find_last_of( const CharT* s, size_type pos = npos ) const; |
(3) | (C++20 起为 constexpr) |
size_type find_last_of( CharT ch, size_type pos = npos ) const; |
(4) | (C++11 起无异常抛出) (C++20 起为 constexpr) |
template< class StringViewLike > size_type |
(5) | (C++17 起) (C++20 起为 constexpr) |
查找与给定字符序列中某个字符相等的最后一个字符。具体的搜索算法未指定。搜索只考虑范围 [
0,
pos]
。如果给定字符序列中的任何字符在该范围内都不存在,则返回 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 时才参与重载决议。
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) |
[编辑] 返回值
找到的字符的位置,如果未找到此类字符则为 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() { const std::string path = "/root/config"; auto const pos = path.find_last_of('/'); const auto leaf = path.substr(pos + 1); std::cout << leaf << '\n'; }
输出
config
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 141 | C++98 | 重载 (1) 仅当 pos >= size() 时才能返回 npos | 搜索范围为[ 0, size()) 在此情况下 |
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 意外删除 |
恢复 |
[编辑] 参阅
查找给定子字符串的第一次出现 (public member function) | |
查找子串的最后一次出现 (public member function) | |
查找字符的首次出现 (public member function) | |
查找字符的首次缺席 (public member function) | |
查找字符的最后一次缺席 (public member function) | |
查找字符的最后一次出现 ( std::basic_string_view<CharT,Traits> 的公开成员函数) |