fork(1) download
  1. #include <algorithm>
  2. #include <cctype>
  3. #include <iomanip>
  4. #include <iostream>
  5. #include <map>
  6. #include <string>
  7. #include <queue>
  8.  
  9.  
  10.  
  11.  
  12.  
  13. inline bool isWordLetter(char c)
  14. {
  15. return std::isalnum(c) || c == '_';
  16. }
  17.  
  18.  
  19. inline void skipws(std::queue<char>& q)
  20. {
  21. while (!( q.empty() || isWordLetter(q.front()) ))
  22. q.pop();
  23. }
  24.  
  25.  
  26. /* Extracts valid word.
  27.  * Returns word or empty string if no word found till the end of queue
  28.  */
  29. std::string extractWord(std::queue<char>& q)
  30. {
  31. std::string word;
  32. bool again = false;
  33. do {
  34. again = false;
  35. skipws(q);
  36. /* Extract all consequent word character */
  37. while( !q.empty() && isWordLetter(q.front()) ) {
  38. word += q.front();
  39. q.pop();
  40. }
  41. /* Check if word extracted is actually word */
  42. if (word.size() < 2 || count_if(word.begin(), word.end(), isalpha) == 0) {
  43. word.clear();
  44. if ( !q.empty() )
  45. again = true;
  46. }
  47. } while (again); //Repeat until we find word or exhaust our queue
  48. std::transform(word.begin(), word.end(), word.begin(), tolower);
  49. return word;
  50. }
  51.  
  52.  
  53. std::string getEnvString()
  54. {
  55. extern char **environ; // needed to access your execution environment
  56. std::string envstr;
  57. int k = -1;
  58. while (environ[++k] != NULL) {
  59. envstr += environ[k];
  60. envstr += '\n';
  61. }
  62. return envstr;
  63. }
  64.  
  65.  
  66. int main()
  67. {
  68. std::string envstr = getEnvString();
  69. std::cout << envstr << std::endl;;
  70.  
  71. std::queue<char> line( {envstr.begin(), envstr.end()} );
  72. size_t wordCount = 0;
  73. std::map<std::string, unsigned> entries;
  74. std::string word;
  75. while((word = extractWord(line)) != "" ) {
  76. ++wordCount;
  77. ++entries[word];
  78. }
  79. std::cout << "There is " << wordCount << " words in envstring\n" <<
  80. "Unique words and their frequency:\n";
  81. for(auto& p: entries) {
  82. std::cout << std::setw(30) << p.first << ' ' << p.second << '\n';
  83. }
  84. }
  85.  
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
TMPDIR=/tmp/GOWirz
PATH=/usr/local/bin:/usr/bin:/bin
PWD=/home/uHkJJI
LANG=en_US.UTF-8
HOME=/home/uHkJJI
SHLVL=0

There is 20 words in envstring
Unique words and their frequency:
                           bin 3
                         en_us 1
                        gowirz 1
                          home 3
                          lang 1
                         local 1
                          path 1
                           pwd 1
                         shlvl 1
                           tmp 1
                        tmpdir 1
                        uhkjji 2
                           usr 2
                           utf 1