【问题标题】:How do i check if theres 2 substring in a string?如何检查字符串中是否有 2 个子字符串?
【发布时间】:2021-04-26 05:02:21
【问题描述】:

我想检查一个字符串中是否存在 2 个子字符串 比如:

string main_string = 'Hello "sir"';

我想检查该字符串是否包含 2 ",必须包含 2。 我也想检查一下:

string main_string = 'Bruh (moment)';

我想检查该字符串是否同时包含()

【问题讨论】:

  • C++ 中的字符串文字由双引号 ("...") 分隔,而不是由单引号 ('...') 分隔,例如:string main_string = "Bruh (moment)"; 如果您需要在字符串,您必须使用\ 转义它们,例如:string main_string = "Hello \"sir\"";
  • 您好,包括我在内的许多用户都与您同在。鼓励解释反对票,但令人失望的是很少这样做。但是,您似乎错过了一个有意的设计决定:stackoverflow.com/help/why-vote 即StackOverflow 想要投票(上下)并决定通过允许匿名投票来保护选民免受报复。因此,匿名投票的用户正在按照允许和赞赏的方式进行操作,尽管这样做时有解释以帮助改进当然会更受欢迎。

标签: c++ find substring


【解决方案1】:

在这两种情况下,您都可以使用std::string::find()

std::string main_string = "Hello \"sir\"";
std::size_t pos = main_string.find('"');
if (pos != std::string::npos)
{
    pos = main_string.find('"', pos+1);
    if (pos != std::string::npos)
    {
       ...
    }
}
std::string main_string = "Bruh (moment)";
std::size_t pos = main_string.find('(');
if (pos != std::string::npos)
{
    pos = main_string.find(')', pos+1);
    if (pos != std::string::npos)
    {
       ...
    }
}

在第一种情况下,您也可以改用std::count()

#include <algorithm>
std::string main_string = "Hello \"sir\"";
std::size_t cnt = std::count(main_string.begin(), main_string.end(), '"');
if (cnt == 2)
{
    ...
}

【讨论】:

  • 性能怎么样?我认为一个循环就足够了,但是当使用 STL 时,我们似乎循环了两次。
  • @prehistoricpenguin 如果您使用 STL 会导致多个循环,那么您可能使用错了
猜你喜欢
  • 2017-10-11
  • 2013-05-12
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 2011-02-07
  • 1970-01-01
相关资源
最近更新 更多