【问题标题】:C++ string checks substring with find_first_of function from std libC++ 字符串使用 std lib 中的 find_first_of 函数检查子字符串
【发布时间】:2019-04-02 17:21:40
【问题描述】:

我想使用 C++ 库中的 find_first_of 函数来检查字符串是否包含某个子字符串,结果与我预期的不太一样。

我有如下代码

const std::wstring_view expected{ L"abc-1" };

const std::wstring_view result = GetResult(); // result = L"abc-2-1" from function return 

if (result.find_first_of(expected) == 0) {
    .....
}

当我调试它时,代码运行到 if 范围,这意味着它从位置“0”找到了匹配的子字符串。这是这个api预期的工作方式吗?我想我可能在这里遗漏了一些东西。

【问题讨论】:

标签: c++ string substring


【解决方案1】:

std::basic_string_view::find_first_of 返回字符串中任何字符第一次出现的位置(如果没有找到,则返回std::basic_string_view::npos)。

换句话说,它给出了第一个'a''b''c''-''2''1' 的位置。

使用std::basic_string_view::find 获取第一个完整子串的位置。

if (result.find(expected) == 0) {
  // ...
}

【讨论】:

  • 知道了,谢谢。我从参考文档中误解了。你说得对,我应该选择 find 而不是 find。
猜你喜欢
  • 2011-02-18
  • 2011-02-24
  • 2015-07-14
  • 1970-01-01
  • 2021-12-20
  • 2015-04-02
  • 2014-08-12
  • 2015-11-13
  • 2011-02-07
相关资源
最近更新 更多