2012-03-05 4 views
0

STLアルゴリズムを使用して、指定された位置から段落内の単語数をカウントする方法はありますか?STLを使用した単語数

+0

(http://mattgemmell.com/2008/12/08/what-have-you-tried/)[何を試してみましたか]? –

答えて

2
#include <algorithm> 
#include <cctype>  
#include <functional> 
#include <string> 


inline unsigned CountWords(const std::string& s)   
{  
std::string x = s; 
std::replace_if(x.begin(), x.end(), std::ptr_fun <int, int> (std::isspace), ' '); 
x.erase(0, x.find_first_not_of(" ")); 
if (x.empty()) return 0; 
return std::count(x.begin(), std::unique(x.begin(), x.end()), ' ') + !std::isspace(   *s.regin());   
} 
+0

この優れた答えの説明が必要な方には、以下が役立ちます。 std :: replace_ifはすべての空白文字をスペースで置き換えます。消去を呼び出すと、すべての空白文字が文字列の先頭から削除されます。 std :: uniqueの呼び出しは、すべての連続した重複スペースが削除された新しい文字列を返します。 std :: countの呼び出しは、std :: uniqueが返す文字列中の空白の数を返します。最後に、元の文字列がスペース内で始まるかどうかによって、0または1のいずれかが結果のカウントに加算されます。 –

0
int count_words(const char *input_buf) { 
    stringstream ss; 
    ss << input_buf; 
    string word; 
    int words = 0; 
    while(ss >> word) words++; 
    return words; 
} 
関連する問題