c++中的单词搜索

Word search in C++

本文关键字:搜索 单词 c++      更新时间:2023-10-16

我编写了一个在文本文件中查找单词的代码。代码工作得很好,但问题是,我需要搜索是否存在确切的词,但它给出了相同的结果,即使它只是另一个词的一部分。例如,我正在寻找单词"Hello",但它说已经存在,因为txt文件有单词"Hello_World",这是不一样的,但包括它。我怎样才能检查准确的单词而忽略其他的呢?我想对单词的长度做点什么,忽略更长一些的东西,但不确定。代码在这里:

cout << "n Type a word: ";
    getline(cin, someword);
    file.open("myfile.txt");
    if (file.is_open()){
        while (!file.eof()){
            getline(file, line);
            if ((offset = line.find(someword, 0)) != string::npos){
                cout << "n Word is already exist!! " << endl;
                file.close();
            }
        }
        file.close();
    }
string line;
getline(file, line);
vector<string> words = TextToWords(line);
if (find(words.begin(), words.end(), someword) != words.end())
    cout << "n Word already exists.n";

TextToWords的实现取决于您。或者使用正则表达式库

使用以下代码拆分单词并搜索所需的单词:

#include <sstream>
stringstream ss(line);
while (getline(ss, tmp, ' ')){
    if (tmp == someword){
        //found
    }
}