Information
Before writing any code, you should write down the steps (in English or your native language) you need to take to solve these problems. This is your pseudocode. Once you have your pseudocode written, you can convert it into C code. If you can't write down the steps in English, you certainly can't write it in C.
Both of the functions you'll be writing deal with NUL-terminated C-style strings. The only header file you can include is string.h, and you'll only need the strlen function.becomesFour score and seven years ago
Notice that you are not reversing the characters in the words, just the words. The function prototype is:ago years seven and score Four
The input is a valid NUL-terminated C-style string and the output is the same size as the input, so you will have enough room for all of the characters including the NULL terminator.void reverse_words1(const char input[], char output[]);
Hint: Walk the input string backwards looking for a space character. Then copy each character of the word to its right into the output. Do this until you get to the beginning of the string and copy the first word as the last word of the output.
If you need a hint, here are some diagrams to help get you started.
Approximate number of lines of code: 25.
There's a clever trick that will make this easier than the first reverse function. First, reverse the entire string character-by-character:void reverse_words2(char input[]);
becomesThis is a string
This is pretty trivial to do. You'll notice that all of the words are in their proper position. They're just reversed. Now, simply reverse the letters of each word. To make this simpler, you should create a helper function that reverses all of the characters between two pointers:gnirts a si sihT
You can even use this function to reverse the entire string at the start./* Helper function to reverse a range a characters */ void reverse(char *start, char *end) { /* Reverse the characters from start to end */ }
Approximate number of lines of code: 15.
This is a partial reversewords.c with functions to get you started.gcc -O -Werror -Wall -Wextra -ansi -pedantic main.c reversewords.c -o reverse
|
Notice the use of the #if 0 ... #endif in the file. This is a simple way to enable/disable a bunch of code in the file. You shouldn't try to pass every test at once. Work on the first test, which is very simple. When you get that test working, move the #if 0 around the next one and see if you pass that test. Continue in this way until you pass all of the tests. All the header files that you need are already included.