【发布时间】:2012-03-05 07:47:23
【问题描述】:
如何使用STL算法从指定位置统计段落中的单词数?
【问题讨论】:
标签: algorithm visual-c++ stl
如何使用STL算法从指定位置统计段落中的单词数?
【问题讨论】:
标签: algorithm visual-c++ stl
#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() );
}
【讨论】:
int count_words(const char *input_buf) {
stringstream ss;
ss << input_buf;
string word;
int words = 0;
while(ss >> word) words++;
return words;
}
【讨论】: