show code
#include <iostream>
#include <string>
int main()
{
std::string str = "hello world";
std::string sign = "wo";
std::cout << "position: " << str.find_first_of(sign) << std::endl;
return 0;
}
- 结果
position: 4 // 请注意是4不是6!!
原因
- 看下string的find_first_of 的语法
size_type find_first_of( const basic_string& str, size_type pos = 0 )
const;(until C++11)
size_type find_first_of( const basic_string& str,size_type pos = 0 )
const noexcept; (since C++11)(until C++20)
...
- 说明
Finds the first character equal to one of the characters in the given character sequence. The search considers only the interval [pos, size()). If the character is not present in the interval, npos will be returned.
- 也就是说,匹配的是字符串的任意字符而不是整个字符串。
- string::find_last_of 也是如此。
参考
起因
// 第一眼没看懂的代码
std::size_t found = str.find_last_of("/\\")