std::basic_string<CharT,Traits,Allocator>::find_first_of_C++中文网

C++ 参考手册

位置:首页 > C++ 参考手册 >字符串库 >std::basic_string > std::basic_string<CharT,Traits,Allocator>::find_first_of

寻找等于给定字符序列中字符之一的首个字符。搜索只考虑区间 [pos, size()) 。若区间中不存在字符,则返回 npos 。

1) 寻找等于 str 中字符之一的首个字符。
2) 寻找等于范围 [s, s+count) 中字符中字符之一的首个字符。此范围能包含空字符。
3) 寻找等于 s 所指向的字符串中字符之一的首个字符。由首个空字符,用 Traits::length(s) 确定字符串长度。
4) 寻找等于 ch 的首个字符。
5) 如同用 std::basic_string_view<CharT, Traits> sv = t; 隐式转换 t 为 string_view sv ,然后寻找等于 sv 中字符之一的首个字符。此重载仅若 std::is_convertible_v<const T&, std::basic_string_view<CharT, Traits>> 为 true 且 std::is_convertible_v<const T&, const CharT*> 为 false 才参与重载决议。

参数

str - 鉴别要搜索的字符的 string
pos - 搜索开始的位置
count - 鉴别要搜索的字符的字符串长度
s - 指向鉴别要搜索的字符的字符串的指针
ch - 鉴别要搜索的字符的字符
t - 鉴别要搜索的字符的对象(可转换为 std::basic_string_view )

返回值

找到的字符的位置,或若找不到这种字符则为 npos 。

异常

5)
noexcept 规定:  
noexcept(std::is_nothrow_convertible_v<const T&, std::basic_string_view<CharT, Traits>>)

注意

用 Traits::eq() 进行比较。

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

DR 应用于 出版时的行为 正确行为
LWG 2946 C++17 string_view 重载在某些情况下导致歧义 通过使之为模板来避免

示例

#include <iostream>
#include <string>
 
int main()
{
    // 测试字符串
    std::string str = std::string("Hello World!");
 
    // 搜索用的字符串和字符
    std::string search_str = std::string("o");
    const char* search_cstr = "Good Bye!";
 
    std::cout << str.find_first_of(search_str) << '\n';
    std::cout << str.find_first_of(search_str, 5) << '\n';
    std::cout << str.find_first_of(search_cstr) << '\n';
    std::cout << str.find_first_of(search_cstr, 0, 4) << '\n';
    // 'x' 不在 "Hello World' 中,从而它将返回 std::string::npos
    std::cout << str.find_first_of('x') << '\n';
}

可能的输出:

4
7
1
4
18446744073709551615

参阅