2012-03-05 35 views
0

如何使用STL算法計算從指定位置開始的段落中的字數?使用STL的字數

+0

[你嘗試過什麼(http://mattgemmell.com/2008/12/08/what-have-you-tried/)? – 2012-03-05 08:00:00

回答

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添加到結果計數中。 – 2015-06-28 05:35:21

0
int count_words(const char *input_buf) { 
    stringstream ss; 
    ss << input_buf; 
    string word; 
    int words = 0; 
    while(ss >> word) words++; 
    return words; 
}