I want reverse the string in particular format.
For exa开发者_开发技巧mple, "My name is Nishant"
should be converted to "Nishant is name My"
.
If you have your words in a char[] words
array then it is a simple loop:
for (i = 0; i < mid; i++)
exchange(words[i], words[number_of_words - i]);
for sane definitions of mid
, number_of_words
and exchange
.
If all you have is a big char containing the entire statement, doing a strtok
first is helpful. Then, use the above loop.
Give our regards to your instructor. If this is a homework assignment, you should write the code yourself.
Here is a little hint, though: use a char pointer to iterate through each character in the array until you hit the NUL terminator at the end. Now iterate in reverse until you hit a space. Save your place in another pointer, move forward by one then copy each of the characters up to but not including the NUL into your output buffer.
Now retrieve the position of that last space in that other pointer where you saved your place, and back up again. When you move forward, you actually need to stop when you encounter either a space of a NULL - ASCII '\0' or a zero byte - and not just a NUL.
It would be a little faster if you save the positions of each of the spaces in some kind of list as you iterate forward at the beginning. That way you don't then need to iterate backward over the entire string, with short iterations over each word. The code would be a little more complicated.
The increased efficiency would be insignificant for short strings like individual English sentences, but would be quite a lot of you were reversing a large file that you just read into memory.
精彩评论