Strings Lab Exercise
You are to write a program with two helper functions as described below. Your program will prompt the user to input a sentence, which you will input with the gets function (syntax: gets(str);). Your program will then print the sentence with the order of the words reversed.
An example run of the program, with user input underlined:
Enter a sentence: you can cage a swallow can't you
Reversal of sentence: you can't swallow a cage can you
You should provide two helper functions:
void replace_whitespace(char *str);
/* replaces every whitespace character in str with the null
character; uses the function isspace(char c) from ctype.h */
int get_words(char *line, char tokens[MAX_WORDS][MAX_LEN+1]);
/* Goal: to store the words from string line in the array
tokens, one word per entry. */
Suggestion:
Have the function compute the length len of the string line, then call replace_whitespace(line).
Each separate word in the array line is now followed by one or more null characters. Next find the start of each word in the array and use strcpy to enter the word in the array of token strings (second parameter)
You can use either a pointer or index to find the first letter of each word. If you pass a pointer to that character as the second argument of strcpy, it will copy the word starting at that position, since it is now null-terminated. You then have to skip over null characters to find the start of the next word.
Warning: you must use a count of all characters traversed (both null characters and characters read into one of the entries in token) to make sure you do not go beyond the end of the original string input into the array line.