-1

I have code that finds the same words with help specific word. Now, I try make code that finds and counts the same words in a string like that: "hello hello hello bye bye" => hello - 3, bye -2

int main()
{
    char str[100], word[20];
    int i, j, ls, lw, temp, countW = 0, chk;
    printf("Enter the String: ");
    gets(str);
    printf("Enter a Word: ");
    gets(word);
    ls = strlen(str);
    lw = strlen(word);
    for (i = 0; i < ls; i++)
    {
        temp = i;
        for (j = 0; j < lw; j++)
        {
            if (str[i] == word[j])
                i++;
        }
        chk = i - temp;
        if (chk == lw)
            countW++;
        i = temp;
    }
    printf("\nOccurrence = %d", countW);
    getch();
    return 0;
}
emblox
  • 37
  • 5
  • 3
    Never ***ever*** use `gets`! It's so [dangerous](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) that it was even removed from the C language over ten years ago (and was deprecated long before that). Use e.g. [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead. What or whom taught you to use `gets` should be viewed with a healthy dose of skepticism. – Some programmer dude Apr 05 '23 at 17:01
  • What is the question? Are you supposed to extract the words from the sentence and find the occurrence of each? – Weather Vane Apr 05 '23 at 17:07
  • 1
    You need a map of `struct { char *word; size_t count; }` (btw, if you also `size_t word_len` then you can just point to the word in `str`). Extract a word from `str` then either increment the relevant count or add a new word with `count = 1` f you don't have a lot of words (<1000) you can just an array, either resized as needed, or big enough to hold all your words. If you have a lot of words use a hash table or a tree to implement your map. – Allan Wind Apr 05 '23 at 17:19
  • 1
    Another option option is create an index of `struct { char *word }` (again you could use `size_t word_len` but no no count). Extract word and always add it to the array. Sort the index (using `strcmp()` as compare function). Now when you iterate through the index and duplicates will be consecutive {bye, bye, hello, hello, hello}. If your input is already sorted then you just need to walk the array. – Allan Wind Apr 05 '23 at 17:26

1 Answers1

1

Thats right , well spotted, so to avoid this "problem" we could use strtok_r

#include <stdio.h>
#include <string.h>

int main() {
   char str[100], word[20], *ptr,*saveptr;
   int count = 0;
   
   printf("Enter a string: ");
   fgets(str, 100, stdin);
   
   // tokenize the string by space
   ptr = strtok_r(str, " ",&saveptr);
   
   while(ptr != NULL) {
      strcpy(word, ptr); // copy current token to word
      count = 1; // reset count to 1 for each new word
      
      // loop through the rest of the string to find the same word
      while((ptr = strtok(NULL, " ")) != NULL) {
         if(strcmp(ptr, word) == 0) { // if same word is found
            count++; // increment count
         }
      }
      
      // print the word and its count if repeated
    if(count>1){
      printf("%s - %d\n", word, count);
         }
     
      
      // get next token
      ptr = strtok_r(NULL, " ",&saveptr);
   }
   
   return 0;
}
PatoDev
  • 11
  • 1