簡體   English   中英

在文本文件中查找單詞並在 C++ 中顯示該單詞的起始位置

[英]Find a word in a text file and show the starting position of that word in C++

我目前正在做一個大學項目,在項目中我應該打開一個 .txt 文件並獲取用戶輸入的單詞並在文本文件中搜索是否有任何匹配,如果程序找到一個或多個單詞,它應該輸出起始詞的位置。 我寫了這段代碼,但它不能完全工作,我做錯了什么或有什么建議嗎? 真的很感激。

    Myfile.open("Test.txt", ios::in);
    if (Myfile.is_open())
    {
        string line,search;
        int i, j=0,x,y,z=-1;
        while (getline(Myfile, line))
        {
            cin >> search;
            x = line.size();
            y = search.size();
            for ( i = 0; i <= x; i++)
            {
                if (line[i]==search[j])
                {
                    z++;
                    j++;
                    if (z==y)
                    {
                        cout << i-y << " " ;
                        z -= y - 1;
                        j -= y -1;
                    }
                }
                if (i==x)
                {
                    cout << "     That's all I've Found :)  ";
                    break;
                }
            }
        }
    } ```

您可以為該任務使用 std::string::find 方法,而不是編寫自己的容易出錯的代碼,該方法只返回您需要的內容: https : //www.cplusplus.com/reference/string/string/find / . 如果您需要編寫自己的代碼而不使用內置方法,請搜索現有的模式匹配算法,例如 Boyer-Moore 或 KMP。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM