【问题标题】:find_first_of with multiple characters doesn't return string::npos when substring shouldn't be present当不应存在子字符串时,具有多个字符的 find_first_of 不返回 string::npos
【发布时间】:2020-11-30 01:09:21
【问题描述】:

我写了一个这样的小sn-p:

#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


    【解决方案1】:

    这是 API 的行为方式:

    查找与 str 中的一个字符相等的第一个字符。

    https://en.cppreference.com/w/cpp/string/basic_string/find_first_of

    【讨论】:

    • 谢谢。我不清楚它的行为方式。
    【解决方案2】:

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

    您应该使用std::string::find

    【讨论】:

    • 谢谢。我不清楚它的行为方式。
    猜你喜欢
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 2020-09-15
    相关资源
    最近更新 更多