find_first_of 多个字符不 return string::npos 当不应该出现子字符串时
find_first_of with multiple characters doesn't return string::npos when substring shouldn't be present
我写了一个这样的小片段:
#include <string>
#include <iostream>
int main() {
std::string s1{"abcdefghijklmnop"};
std::cout << "s1(fg) = " << s1.find_first_of("fg") << '\n';
std::cout << "s1(fo) = " << s1.find_first_of("fo") << '\n';
}
我预计它 returns 5 和 string::npos,但实际上 returns
s1(fg) = 5
s1(fo) = 5
为什么会这样?
我的编译标志和 g++ 版本:
$ g++ -std=c++11 main.cpp
$ g++ --version
g++.exe (Rev1, Built by MSYS2 project) 10.2.0
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
std::string::find_first_of
returns 您提供给它的字符的 any 的位置。在您的情况下,它两次都找到 f
。
你应该使用 std::string::find
.
这是 API 的行为方式:
Finds the first character equal to one of the characters in str.
https://en.cppreference.com/w/cpp/string/basic_string/find_first_of
我写了一个这样的小片段:
#include <string>
#include <iostream>
int main() {
std::string s1{"abcdefghijklmnop"};
std::cout << "s1(fg) = " << s1.find_first_of("fg") << '\n';
std::cout << "s1(fo) = " << s1.find_first_of("fo") << '\n';
}
我预计它 returns 5 和 string::npos,但实际上 returns
s1(fg) = 5
s1(fo) = 5
为什么会这样?
我的编译标志和 g++ 版本:
$ g++ -std=c++11 main.cpp
$ g++ --version
g++.exe (Rev1, Built by MSYS2 project) 10.2.0
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
std::string::find_first_of
returns 您提供给它的字符的 any 的位置。在您的情况下,它两次都找到 f
。
你应该使用 std::string::find
.
这是 API 的行为方式:
Finds the first character equal to one of the characters in str.
https://en.cppreference.com/w/cpp/string/basic_string/find_first_of