如何使用STL算法从指定位置计算段落中的单词数?
答案 0 :(得分: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() );
}
答案 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;
}