在字符串中查找多个子字符串

时间:2019-05-04 20:00:08

标签: c++

所以,我想输出一些[]内的代码,但问题是:它只显示第一个当前值,而第二个等等都没有显示。

已经尝试使用vector来做到这一点,但没有成功。

std::string get_line(std::string s, std::string start_delim,
        std::string stop_delim)
{
    unsigned first_delim_pos = s.find(start_delim);
    unsigned end_pos_of_first_delim = first_delim_pos + start_delim.length();
    unsigned last_delim_pos = s.find(stop_delim);

    return s.substr(end_pos_of_first_delim,
            last_delim_pos - end_pos_of_first_delim);
}

int main()
{
    string word = "[this] is a [test]";
    std::vector<std::string> list;

    for (int i= 0; i < 2; ++i)
    {
        std::string start_line = "[";
        std::string stop_line = "]";
        std::string l_line_ = get_line(word, start_line, stop_line);

        list.push_back(l_line_);

        cout << " The word is: " << list[i] << endl;
        cout << endl;
    }
}

因此,正如我所说,我希望输出为:

The word is: this
The word is: text

但是显示的是:

The word is: this
The word is: this

1 个答案:

答案 0 :(得分:2)

只需编写一个函数,该函数将返回字符串向量,并记住上一个结束位置并从该位置继续:

std::vector<std::string> get_words( const std::string &text, 
                                    const std::string &b,
                                    const std::string &e )
{
    std::vector<std::string> r;
    std::string::size_type epos = 0;
    while( true ) {
        auto bpos = text.find( b, epos );
        if( bpos == std::string::npos ) break;
        bpos += b.length();
        epos = text.find( e, bpos );
        if( epos == std::string::npos ) break;
        r.push_back( text.substr( bpos, epos - bpos ) );
        epos += e.length();
    }
    return r;
}

您编写的当前函数无法从之前停止的位置继续。

Live example