首页 > 解决方案 > 当不应存在子字符串时,具有多个字符的 find_first_of 不返回 string::npos

问题描述

我写了一个这样的小片段:

#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';
}

我希望它返回 5 和 string::npos,但它实际上返回

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.

标签: c++msys

解决方案


std::string::find_first_of返回您提供给它的任何字符的位置。在您的情况下,它f两次都找到。

你应该使用std::string::find.


推荐阅读