Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- using namespace std;
- const unsigned MAX_SIZE = 1024;
- int countWords(char* str) {
- int cnt = 1;
- while (*str) {
- if (*str == ' ') {
- cnt++;
- }
- str++;
- }
- return cnt;
- }
- void cleanMatrix(char** matrix,int size) {
- for (int i = 0; i < size; i++) {
- delete[]matrix[i];
- }
- delete[] matrix;
- }
- int findWord(const char* const* matrix, int size, const char* target)
- {
- for (int i = 0; i < size; i++)
- if (strcmp(matrix[i], target) == 0)
- return i;
- return -1;
- }
- int main() {
- char str[MAX_SIZE];
- cin.getline(str, MAX_SIZE);
- int numOfWords = countWords(str);
- char** words = new(nothrow) char* [numOfWords];
- if (!words)return 1;
- int* wordsCount = new(nothrow)int[numOfWords];
- if (!wordsCount) return 1;
- char* ptr = strtok(str," ");
- int numunique = 0;
- int i = 0;
- while(ptr!=nullptr){
- int index=findWord(words, i, ptr);
- if (index == -1) {
- words[i] = new (std::nothrow) char[strlen(ptr) + 1];
- if (!words[i]) {
- cleanMatrix(words, i);
- delete[] wordsCount;
- return 1;
- }
- wordsCount[i] = 1;
- strcpy(words[i], ptr);
- ++numunique;
- i++;
- }
- else {
- wordsCount[index]++;
- }
- ptr=strtok(nullptr, " ");
- }
- for (int i = 0; i < numunique; i++) {
- cout << words[i] << " : " << wordsCount[i] << "times";
- }
- cleanMatrix(words, numOfWords);
- delete[]wordsCount;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement