Advertisement
darkn3tc0d3r

word count

Dec 22nd, 2013
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. // split function
  2.  
  3. vector<string> split(const string& s)
  4. {
  5. vector<string> ret;
  6. typedef string::size_type string_size;
  7. string_size i = 0;
  8. // invariant: we have processed characters [original value of i, i)
  9. while (i != s.size()) {
  10. // ignore leading blanks
  11. // invariant: characters in range [original i, current i) are all spaces
  12. while (i != s.size() && isspace(s[i]))
  13. ++i;
  14. // find end of next word
  15. string_size j = i;
  16. // invariant: none of the characters in range [original j, current j)is a space
  17. while (j != s.size() && !isspace(s[j]))
  18. j++;
  19. // if we found some nonwhitespace characters
  20. if (i != j) {
  21. // copy from s starting at i and taking j - i chars
  22. ret.push_back(s.substr(i, j - i));
  23. i = j;
  24. }
  25. }
  26. return ret;
  27. }
  28.  
  29. The main should be something like :
  30.  
  31.  
  32. #include <iostream>
  33. #include <map>
  34. using namespace std;
  35. vector<string> split(const string& s);
  36. int main()
  37. {
  38. string s;
  39. map<string, int> counters; // store each word and an associated counter
  40. // read the input, keeping track of each word and how often we see it
  41. while (cin >> s)
  42. ++counters[s];
  43. // write the words and associated counts
  44. for (map<string, int>::const_iterator it = counters.begin(); it != counters.end(); ++it) {
  45. cout << it->first << "\t" << it->second << endl;
  46. }
  47. return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement