Need help with #6, i don’t know how to sort through my array of pointers to stri
ID: 3741754 • Letter: N
Question
Need help with #6, i don’t know how to sort through my array of pointers to strings and determine which ones end in “dous” and store them in an array. I have a function that finds the longest word already. Your program is to read in the contents of the dictionary provided into a dynamically allocated array of pointers to strings, e.g. char *Words [NUM WORDS] so that the array requires the minimum amount of storage for each word. Operation Your program should examine those words and find which words have the following properties: 1. The longest word(s) typed only with the right hand. 2. The longest word(s) typed only with the left hand 3. The longest word(s) typed with only the first letter row of the keyboard. 4. The longest word(s) typed with only the second letter row of the keyboard. 5. The longest word(s) typed with only the third letter row of the keyboard. 6. All words and longest word ending in 'dous.Explanation / Answer
You can use the following code-snippet to see if any given "word" ends with any other given string (e.g dous or anything else)
int ends_with(char *word, char *end_letters) {
int word_len = strlen(word);
int end_len = strlen(end_letters);
if(end_len > word_len) {
// Word is smaller than end_string, so definitley return FALSE
return 0;
} else {
// Slice the word till the length of end_letters
char *slice = word+(word_len - end_len);
// Compare the end_letter with one another
if(strstr(slice, end_letters)== NULL) {
// The "word" does not end with the given "end_letters"
return 0;
} else {
// The "word" indeed ends with the given "end_letters"
return 1;
}
}
}
Usage:
Fromt the main, you can call this function like:
main () {
...
Your dictionary/word list is is in char *Words[NUM_WORDS]
...
for(int i=0; i< NUM_WORDS; i++) {
char *longest = NULL;
if(ends_with(Words[i], "dous") != 0) {
// This word ends with "dous
printf("%s ", Words[i]);
if(strlen(Words[i]) > strlen(longest)) {
longest = Words[i];
}
}
printf("Longest word ending with dous is: %s ", Words[i]);
}
}