Created
October 21, 2023 20:26
-
-
Save amanullahmenjli/7e728b859afc4165e5ceff2ccea93d01 to your computer and use it in GitHub Desktop.
A C program to count how many times each word in a given sentence are repeated
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <string.h> | |
| int main(){ | |
| // Get a sentence of a maximum length of 100 characters from the user | |
| char sentence[100]; | |
| printf("Enter your sentence: "); | |
| gets(sentence); | |
| // The table to hold the words (maximum 100 words) | |
| // Each word has maximum length of 50 characters | |
| char words[100][50]; | |
| // The table to hold word occurrences | |
| int occurrences[100]; | |
| // Initialize each element of the occurrences table to 0 | |
| for (int i = 0; i < 100; ++i){ | |
| occurrences[i] = 0; | |
| } | |
| // A variable to track where to add words in the table | |
| int discovered_words = 0; | |
| // A variable to store each word temporarily before going to the table | |
| char temp_word[50]; | |
| // Go through the whole sentence character by character | |
| for (int c = 0; c <= strlen(sentence); ++c){ | |
| // If a space or the end of the file is found add the current word or increase its occurrences count | |
| // Otherwise keep reading the current word | |
| if (sentence[c] == ' ' || sentence[c] == '\0' || sentence[c] == '\r' || sentence[c] == '\t'){ | |
| // Search for the word in the words table, if exists increase its occurences | |
| // otherwise add it and increase its occurences and the discovered words | |
| int found = 0; | |
| for (int w = 0; w < discovered_words; ++w){ | |
| if (strcmp(words[w], temp_word) == 0){ | |
| occurrences[w]++; | |
| found = 1; | |
| } | |
| } | |
| if (found == 0){ | |
| strcpy(words[discovered_words], temp_word); | |
| occurrences[discovered_words]++; | |
| discovered_words++; | |
| } | |
| // Reset the temporary word after we're done with it | |
| for (int i = 0; i < strlen(temp_word); ++i){ | |
| temp_word[i] = '\0'; | |
| } | |
| } | |
| else{ | |
| strncat(temp_word, &sentence[c], 1); // Add the current character to word variable | |
| } | |
| } | |
| // Show the results | |
| for (int word = 0; word < discovered_words; ++word) | |
| { | |
| printf("Le mot %s est repeté %d fois\n", words[word], occurrences[word]); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment