C ++从字符串中删除匹配的单词

时间:2016-08-26 01:39:50

标签: c++ arrays string turbo-c++

我试图从字符串中的句子中删除某些单词(在字符串数组中)。

这里我想从字符串tab中删除数组s中的字符串。到目前为止,我能够打破字符串,但不知道如何检查数组中是否存在特定字符串

#include <iostream>
#include <string>

int main()
{
std::string s("Somewhere down the road");
std::string tab[2]={"The","the","THE"};

std::string::size_type prev_pos = 0, pos = 0;
while( (pos = s.find(' ', pos)) != std::string::npos )
    {
    std::string substring( s.substr(prev_pos, pos-prev_pos) );
    std::cout << substring << '\n';
    prev_pos = ++pos;
    }
std::string substring( s.substr(prev_pos, pos-prev_pos) );
std::cout << substring << '\n';
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

#include <iostream>
#include <string>
#include <stack>
int main()
{
    std::string s("Somewhere down the road");
    std::string tab[3] = { "The", "the", "THE" };

    std::string::size_type prev_pos = 0, pos = 0;
    std::stack<std::pair<int,int>> erase_pairs;
    while ((pos = s.find(' ', pos)) != std::string::npos)
    {
        std::string substring(s.substr(prev_pos, pos - prev_pos));
        std::cout << substring << '\n';
        for (auto t = 0; t < 3;t++)
        {
            if (substring == tab[t])
            {
                erase_pairs.push(std::make_pair(prev_pos, pos - prev_pos));
            }
        }
        prev_pos = ++pos;
    }
    for (auto i = 0; i < erase_pairs.size();i++)
    {
        auto what = erase_pairs.top();//I cheated on my homework
        erase_pairs.pop();
        s.erase(what.first, what.second);
    }
    std::string substring(s.substr(prev_pos, pos - prev_pos));//note you also gotta remove the spaces
    std::cout << substring << '\n';
}