Search code examples
cdistancestrtokwordsrepeat

C , How to find 2 repeating words in a string and count the distance between them


From what i understand i need to use the the strtok function but i have no idea what to do next. Please help.

This is literally how far i've gotten :

printf("Write a sentence\n");
gets(text);
token=strtok(text, " ");

I understand that i have to split the string into segments (words), but i have no idea what do i do after that.


Solution

  • I would use strtok to split the input string into words. Then, I will add each word to a hashtable: the keys would be the words, and the values would be the word's first occurrence position. When inserting a new word into the hashtable, if the world is already there, then I'd compute the distance between the current position and that word's position.

    Hope it helps.