簡體   English   中英

初學者C ++-字符串比較

[英]Beginner C++ - String Comparison

我是一名C#程序員,最近想深入研究某個較低的層次,因此上周開始學習C ++,但偶然發現了我認為相當簡單的內容。

我在程序中輸入以下字符串:

“這是一次測試”,希望wordStructList包含4個單詞的列表,其中“ test”和“ this”的出現設置為2。但是,在調試時,字符串比較(我嘗試過.compare和==)似乎總是會增加出現次數的值,無論比較結果是否正確。

例如currentName =“ is” word =“ this”

但出現的次數仍在增加。

#include "stdafx.h"

using std::string;
using std::vector;
using std::find;
using std::distance;

struct Word
{
    string name;
    int occurrences;
};

struct find_word : std::unary_function<Word, bool> 
{
    string name;
    find_word(string name):name(name) { }
    bool operator()(Word const& w) const 
    {
        return w.name == name;
    }
};

Word GetWordStruct(string name)
{
    Word word;

    word.name = name;
    word.occurrences = 1;

    return word;
}

int main(int argc, char argv[])
{
string s;
string delimiter = " ";
vector<string> wordStringList;

getline(std::cin, s);

do
{
    wordStringList.push_back(s.substr(0, s.find(delimiter)));
    s.erase(0, s.find(delimiter) + delimiter.length());

    if (s.find(delimiter) == -1)
    {
        wordStringList.push_back(s);
        s = "";
    }

} while (s != "");

vector<Word> wordStructList;

for (int i = 0; i < wordStringList.size(); i++)
{
    Word newWord;

    vector<Word>::iterator it = find_if(wordStructList.begin(), wordStructList.end(), find_word(wordStringList[i]));

    if (it == wordStructList.end())
        wordStructList.push_back(GetWordStruct(wordStringList[i]));
    else
    {
        string word(wordStringList[i]);

        for (vector<Word>::size_type j = 0; j != wordStructList.size(); ++j)
        {
            string currentName = wordStructList[j].name;

            if(currentName.compare(word) == 0);
                wordStructList[j].occurrences++;
        }
    }
}

return 0;
}

我希望這個問題有意義。 有人對此有何啟示? 我也歡迎有關如何使代碼更明智/更具可讀性的任何提示。 謝謝

問題是在此if語句之后的分號:

if(currentName.compare(word) == 0);

分號終止該語句,因此下一行

wordStructList[j].occurrences++;

不再是if語句的一部分,將始終執行。

暫無
暫無

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

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