从用户输入C++中删除非索引字

ymdaylpp  于 2022-11-27  发布在  其他
关注(0)|答案(1)|浏览(126)

在名为removeStopWords的函数中,有一个名为original_words的数组,还有一个名为stop_words的数组,我想打印original_words中所有不存在于stop_words中的元素
下面是我的代码,我尝试使用多个条件使用嵌套循环,但它们不起作用:

#include <iostream>
#include <string>

using namespace std;
void removeStopWords(string str);

int main()
{
    string str;
    cout<<"String : ";
    getline(cin, str);
    removeStopWords(str);
    return 0;
}

void removeStopWords(string str)
{
    string stop_words[10] = { "this" , "is " , "a" , "are" , "and" , "as" , "at" , "do" , "hence" , "your"};
    string out[1000] ;
    string original_words[1000] ;
    int length = str.size();
    int BreakWordIndex = 0;
    int index_out = 0;
    string temp;
    int count = 0;

    int number_of_words = 1;
    //loop to counter number of words in the input string
    for(int x = 0; x<length; x++)
    {
        if(str[x] == 32)
        {
            number_of_words++;
        }
    }
    //loop to put all the words of the string in an array
    for ( int i = 0; i<length; i++)
    {
        if(str[i] == 32)
        {
            index_out++;
        }
        else
        {
            original_words[index_out] += str[i];//this
            
        }
        
    }
    //tester loop
    for(int i = 0; i<number_of_words; i++)
    {
        for(int j = 0; j<10; j++)
        {
            if(original_words[i] != stop_words[j])
            {
                out[i] = original_words[i];
            }
        }
        // out[count] = original_words[i];
    }
    // cout<<count;

    for ( int i = 0; i<10; i++)
    {
        cout<<out[i]<<" ";
    }
}
utugiqy6

utugiqy61#

如果希望输入字符串中的单词由空格分隔,则可以从输入字符串创建单词向量:

std::istringstream iss{ str };  // str is the input string
std::vector<std::string> words{
    std::istream_iterator<std::string>{ iss },
    std::istream_iterator<std::string>{}
};

然后,您可以删除stop_words中的单词。注意:

  1. stop_words应该排序,并且
  2. std::erase_if仅在C++20之后可用。
std::erase_if(words, [&stop_words](const std::string& word) {
    return std::ranges::binary_search(stop_words, word); }
);

Demo(https://godbolt.org/z/r3n4zsrjj)
从这里开始需要一些额外工作的事情:

  • 输入字符串中的单词可以用空格以外的其他分隔符(例如标点符号)分隔。
  • 搜索停用词时可能需要区分大小写。

相关问题