如何在考虑标点符号的同时在文件中查找字符串

How to find strings in a file while taking into account the punctuations?

本文关键字:文件 查找 字符串 标点符号      更新时间:2023-10-16

我正在尝试计算某个单词在文本文件中出现的次数。这是我的代码:

int main()
{
    ifstream file("Montreal.txt");
    string str;
    int number = 0;
    while (file >> str){
        if (str == "Toronto"){
            number++;
        }
    }
    cout << number << endl;
    return 0;
}

问题是:

当我要找的单词(在本例中为"Toronto")末尾有一个标点符号,如"Toronto."或"Toronto"时,它不会考虑它。我该如何考虑这些情况?

谢谢

使用 std::string::find()

if (str.find("Toronto") != std::string::npos)
{
    // ...
}

试试这样的事情

        #include <iostream>
        #include <fstream>
        #include <string>
        #include <vector>
        #include <limits>
        #include <sys/stat.h>
        const size_t nErrSize = std::numeric_limits<size_t>::max();
        int CountWord(const std::string &sBuff, const std::string sWord)
        {
            size_t nNext = 0;
            int nCount = 0;
            int nLength = sWord.length();
            while (sBuff.npos != (nNext = sBuff.find(sWord, nNext)))
            {
                   ++nCount;
                   nNext += nLength;
            }
            return nCount;
        }
        #if defined(WIN32)
            #undef stat
            #define stat _stat
        #endif
        size_t GetFileSize(const std::string &sFile)
        {
            struct stat st = { 0 };
            if (0 > ::stat(sFile.c_str(), &st))
                return nErrSize;
            else
                return st.st_size;
        }
        bool Load(const std::string &sFile, std::string &sBuff)
        {
            size_t nSize = GetFileSize(sFile);
            if (nSize == nErrSize)
                return false;
            std::ifstream ifs(sFile, std::ifstream::binary);
            if (!ifs)
                return false;
            std::vector<char> vBuff(nSize);
            ifs.read(vBuff.data(), nSize);
            if (ifs.gcount() != nSize)
                return false;
            sBuff.assign(vBuff.cbegin(), vBuff.cend());
            return true;
        }
        int main()
        {
            const std::string sFile("Montreal.txt");
            const std::string sSearch("Toronto");
            std::string sBuff;
            if (Load(sFile, sBuff))
            {
                std::cout << sSearch
                          << " occurred "
                          << CountWord(sBuff, sSearch)
                          << " times in file "
                          << sFile
                          << "."
                          << std::endl;
                return 0;
            }
            else
            {
                std::cerr << "Error" << std::endl;
                return 1;
            }
        }