Skip to content

Instantly share code, notes, and snippets.

@asm-jaime
Created November 14, 2016 05:12
Show Gist options
  • Save asm-jaime/41889b182e520e532ca163ad07eb3329 to your computer and use it in GitHub Desktop.
Save asm-jaime/41889b182e520e532ca163ad07eb3329 to your computer and use it in GitHub Desktop.
Average occurrence of the first word in sentence
#include <iostream>
#include <regex>
using namespace std;
int main()
{
regex sentense_regex("[^!?.]+");
string all_str;
string cmp_str;
size_t num_sts;
size_t num_cmp;
double average_num;
getline(cin,all_str);
if((num_cmp = all_str.find(' ')) != string::npos)
{
cmp_str = all_str.substr(0, num_cmp);
}
else
{
cout << "have't string!"<< endl;
return 0;
}
regex word_regex(cmp_str);
auto sentence_begin = sregex_iterator(all_str.begin(), all_str.end(), sentense_regex);
auto sentence_end = sregex_iterator();
num_sts = distance(sentence_begin, sentence_end);
for (sregex_iterator i = sentence_begin; i != sentence_end; ++i)
{
smatch match = *i;
string match_str = match.str();
auto words_begin = sregex_iterator(match_str.begin() + 1, match_str.end(), word_regex);
auto words_end = sregex_iterator();
average_num += static_cast<double>(distance(words_begin, words_end))/num_sts;
}
cout << average_num << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment