2015-05-01 105 views
1

我寫過一個程序來存儲文本文件中的字符向量。計算字符向量中的單詞出現次數

#include<iostream> 
#include<fstream> 
#include <algorithm> 
#include<vector> 
using namespace std; 

int main() 
{ 
    vector<char> vec; 
    ifstream file("text.txt"); 

    if(!file.eof() && !file.fail()) 
    { 
     file.seekg(0, std::ios_base::end); 
     std::streampos fileSize = file.tellg(); 
     vec.resize(fileSize); 

     file.seekg(0, std::ios_base::beg); 
     file.read(&vec[0], fileSize); 
    } 

    int c = count(vec.begin(), vec.end(), 'U'); 
    cout << c; 
    return 0; 
} 

我想在文本文件中計算「USER」的出現次數,但是使用count我只能計算字符數。我如何計算字符向量中「USER」的出現次數?

例如 的text.txt

USERABRUSER#$$* 34 USER ABC RR IERUSER 

然後 「USER」 的計數是4字只能爲大寫。

+1

定義「word」的含義。另外,你的IO不是很正確:在打開之後使用'file.is_open()'進行測試更爲習慣。更重要的是,'file.read'可能會失敗,因爲您計算大小的方式在非Unix平臺上不起作用。 –

+0

我已經更新了這個問題。 –

回答

3

std::string具有find成員函數,將發現裏面另一個串的發生。你可以用它來計算出現這樣的:

size_t count(std::string const &haystack, std::string const &needle) { 
    auto occurrences = 0; 
    auto len = needle.size(); 
    auto pos = 0; 

    while (std::string::npos != (pos = haystack.find(needle, pos))) { 
     ++occurrences; 
     pos += len; 
    } 
    return occurrences; 
} 

例如:

int main() { 
    std::string input{ "USERABRUSER#$$* 34 USER ABC RR IERUSER" }; 

    std::cout << count(input, "USER"); 
} 

...產生的4的輸出。

+0

這解決了這個問題,但我建議使用矢量字符和計數功能....但是,無論如何謝謝... –

2

這是我會怎麼做:

#include <fstream> 
#include <sstream> 
#include <iostream> 
#include <unordered_map> 
#include <string> 

using namespace std; 

int main() { 
    unordered_map<string, size_t> data; 
    string line; 
    ifstream file("text.txt"); 
    while (getline(file, line)) { 
     istringstream is(line); 
     string word; 
     while (is >> word) { 
     ++data[word]; 
     } 
    } 

    cout << data["USER"] << endl; 
    return 0; 
} 
+0

雖然這(至少可以說是)符合最初發布的問題,但它不符合編輯的問題。無論哪種方式,它都可能效率很低,存儲了大量沒有實際使用的數據。這大致相當於回答:「這個老師班有多少個孩子?」通過全國人口普查,然後檢查有多少人在課堂上。 –

+0

你的比喻是錯誤的。我不會增加需要處理的數據大小。我們都處理相同數量的數據(即文件),但是,我會爲每個項目做更多的工作。我的解決方案允許更輕鬆地回答其他問題,並且是更通用的解決方案。可能不會給OP增加任何價值,但對於試圖回答類似問題並需要查詢處理過的數據集中的多個單詞的其他人有用。在任何情況下,如果OP不想將結果存儲在unordered_map中,他/她可以刪除功能並繼續他/她的業務。 –

0

讓我們再試一次。再一次,一個向量不是必需的。這就是我認爲是最常用的C++慣用方法。它使用std::stringfind()方法按順序重複查找子串,直到到達字符串末尾。

#include <fstream> 
#include <iostream> 
#include <string> 

int main() { 
    // Read entire file into a single string. 
    std::ifstream file_stream("text.txt"); 
    std::string file_contents(std::istreambuf_iterator<char>(file_stream), 
     std::istreambuf_iterator<char>()); 

    unsigned count = 0; 
    std::string substr = "USER"; 
    for (size_t i = file_contents.find(substr); i != std::string::npos; 
     i = str.find(substr, i + substr.length())) { 
     ++count; 
    } 
} 
+0

檢查更新後的問題 –

相關問題