【问题标题】:Word count using STL使用 STL 进行字数统计
【发布时间】:2012-03-05 07:47:23
【问题描述】:

如何使用STL算法从指定位置统计段落中的单词数?

【问题讨论】:

标签: algorithm visual-c++ stl


【解决方案1】:
#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() );         
}  

【讨论】:

  • 对于那些需要解释这个出色答案的人,以下内容可能会有所帮助。 std::replace_if 用空格替换所有空白字符。对擦除的调用从字符串的开头删除所有空白字符。对 std::unique 的调用返回一个新字符串,其中删除了所有连续的重复空格。对 std::count 的调用返回 std::unique 返回的字符串中的空格数,从而返回单词数。最后,根据原始字符串是否以空格开头,将 0 或 1 添加到结果计数中。
【解决方案2】:
int count_words(const char *input_buf) {
    stringstream ss;
    ss << input_buf;
    string word;
    int words = 0;
    while(ss >> word) words++;
    return words;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多