简体   繁体   English

C ++中的单词搜索

[英]Word search in C++

I made a code which finds a word in a text file. 我编写了一个在文本文件中找到单词的代码。 The code works fine but the problem is that i need to search if the exact word is existed or not but it gives the same result even if it just part of another word. 该代码工作正常,但问题是我需要搜索是否存在确切的单词,但是即使它只是另一个单词的一部分,它也会给出相同的结果。 Example im looking for the word 'Hello' but it says already existed cos the txt file has the word 'Hello_World' which is not the same but includes it. 例如,我正在寻找单词“ Hello”,但它说该文本文件已经存在,因为txt文件中的单词“ Hello_World”不相同,但包含该单词。 How can i check for the exact word and ignore the others. 我该如何检查确切的单词而忽略其他单词。 Im thinking to do something with the length of the word and ignore anything longer but not sure. 我想用单词的长度做些什么,而忽略更长的时间,但不确定。 The code is here: 代码在这里:

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";

The TextToWords implementation is up to you. TextToWords实现取决于您。 Or use a regular expression library. 或使用正则表达式库。

Use this code to split words and search for the intended one: 使用此代码拆分单词并搜索所需的单词:

#include <sstream>

stringstream ss(line);
while (getline(ss, tmp, ' ')){
    if (tmp == someword){
        //found
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM