我如何检查字符串中是否有 2 个子字符串?

How do i check if theres 2 substring in a string?

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

string main_string = 'Hello "sir"';

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

string main_string = 'Bruh (moment)';

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

在这两种情况下,您都可以使用 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)
{
    ...
}