word count: initial solution.
This commit is contained in:
parent
40834ece6e
commit
fb546d1f29
2 changed files with 67 additions and 3 deletions
|
|
@ -1,12 +1,73 @@
|
||||||
#include "word_count.h"
|
#include "word_count.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
|
||||||
namespace word_count {
|
namespace word_count {
|
||||||
|
|
||||||
using namespace std;
|
using namespace std;
|
||||||
|
|
||||||
Words words(const string &str)
|
|
||||||
|
Words words(const string &str, const locale &loc)
|
||||||
{
|
{
|
||||||
return Words();
|
Words result;
|
||||||
|
|
||||||
|
enum {
|
||||||
|
|
||||||
|
InsideWord,
|
||||||
|
OutsideWord
|
||||||
|
|
||||||
|
} state(OutsideWord);
|
||||||
|
|
||||||
|
|
||||||
|
string::const_iterator begin, end, i;
|
||||||
|
i = begin = end = str.begin();
|
||||||
|
|
||||||
|
for (; i != str.end(); ++i) {
|
||||||
|
|
||||||
|
bool is_alpha_or_digit = isalpha(*i, loc) || isdigit(*i, loc);
|
||||||
|
bool is_word_char = is_alpha_or_digit || *i == '\'';
|
||||||
|
|
||||||
|
switch (state) {
|
||||||
|
|
||||||
|
case OutsideWord:
|
||||||
|
|
||||||
|
if (is_alpha_or_digit) {
|
||||||
|
|
||||||
|
state = InsideWord;
|
||||||
|
begin = i;
|
||||||
|
end = next(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case InsideWord:
|
||||||
|
|
||||||
|
if (is_alpha_or_digit) {
|
||||||
|
|
||||||
|
end = next(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_word_char || next(i) == str.end()) {
|
||||||
|
|
||||||
|
state = OutsideWord;
|
||||||
|
|
||||||
|
if (begin != end) {
|
||||||
|
|
||||||
|
string word;
|
||||||
|
word.reserve(distance(begin, end));
|
||||||
|
transform(begin, end, back_inserter(word),
|
||||||
|
[=](char c){return tolower(c, loc);});
|
||||||
|
|
||||||
|
result[word]++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#define EXERCISM_RUN_ALL_TESTS
|
||||||
|
|
||||||
|
#include <locale>
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
|
|
@ -7,6 +10,6 @@ namespace word_count {
|
||||||
|
|
||||||
typedef std::map<std::string, int> Words;
|
typedef std::map<std::string, int> Words;
|
||||||
|
|
||||||
Words words(const std::string&);
|
Words words(const std::string&, const std::locale &loc = std::locale());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue