Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4.  
  5. const unsigned MAX_SIZE = 1024;
  6.  
  7. int countWords(char* str) {
  8. int cnt = 1;
  9. while (*str) {
  10. if (*str == ' ') {
  11. cnt++;
  12. }
  13. str++;
  14. }
  15. return cnt;
  16. }
  17.  
  18. void cleanMatrix(char** matrix,int size) {
  19. for (int i = 0; i < size; i++) {
  20. delete[]matrix[i];
  21. }
  22. delete[] matrix;
  23. }
  24.  
  25. int findWord(const char* const* matrix, int size, const char* target)
  26. {
  27. for (int i = 0; i < size; i++)
  28. if (strcmp(matrix[i], target) == 0)
  29. return i;
  30. return -1;
  31. }
  32.  
  33.  
  34. int main() {
  35. char str[MAX_SIZE];
  36. cin.getline(str, MAX_SIZE);
  37.  
  38. int numOfWords = countWords(str);
  39.  
  40. char** words = new(nothrow) char* [numOfWords];
  41. if (!words)return 1;
  42.  
  43. int* wordsCount = new(nothrow)int[numOfWords];
  44. if (!wordsCount) return 1;
  45.  
  46. char* ptr = strtok(str," ");
  47. int numunique = 0;
  48. int i = 0;
  49.  
  50. while(ptr!=nullptr){
  51. int index=findWord(words, i, ptr);
  52. if (index == -1) {
  53. words[i] = new (std::nothrow) char[strlen(ptr) + 1];
  54. if (!words[i]) {
  55. cleanMatrix(words, i);
  56. delete[] wordsCount;
  57. return 1;
  58. }
  59. wordsCount[i] = 1;
  60. strcpy(words[i], ptr);
  61. ++numunique;
  62. i++;
  63. }
  64. else {
  65. wordsCount[index]++;
  66.  
  67. }
  68. ptr=strtok(nullptr, " ");
  69.  
  70. }
  71.  
  72. for (int i = 0; i < numunique; i++) {
  73. cout << words[i] << " : " << wordsCount[i] << "times";
  74. }
  75.  
  76. cleanMatrix(words, numOfWords);
  77. delete[]wordsCount;
  78.  
  79. return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement