Hi paul,
Could u provide me with a code snipplet based on ur plan ?
maximteo
Main Topics
Browse All TopicsHi guys, something i couldn't figure out....
Write a function to reverse the order of words
Given a sentence of words in a character array, write a C function to reverse the order of words.
char* reverse_word (char* str);
The function gets a character array as its sole argument, reverses the order of words in it, and puts back the result into it. It returns the pointer to the argument on termination for convenience sake.
See the following example.
char str[] = "this is very beautiful ";
printf ("[%s]\n", reverse_word(str)); /* print [beautiful very is this ] */
Be ware that the position of space characters has not moved; the result of the example above is [beautiful very is this ], not [beautiful very is this ].
The following constraints apply:
No external function calls. (strlen, strcpy, etc).
No explicit memory allocation. (malloc, realloc, dynamic arrays, etc)
I managed only managed to reverse the order of words which results in [beautiful very is this ], however I didn't know how to maintain the position of space characters [beautiful very is this ].
this is the code that i wrote:
#include <stdio.h>
char* reverse_word(char* s)
{
char *str = s;
int len = string_len(s);
int i=0;
int count=0;
reverse_substring(str,0,po
while(i<=len){
if(str[i] ==' ' || i==len){
reverse_substring(str,i-co
count=0;
}
if(str[i]!=' '){
count++;
}
i++;
}
return str;
}
int pos_lastChar(char* s)
{
int i;
for(i=string_len(s); i>0;i--){
if (s[i]!=' ' && s[i]!='\0'){
return i;
}
}
}
reverse_substring(char* s, int start, int end)
{
char temp;
int i,j;
for(i=start, j=end; i<j; i++,j--)
{
temp = s[i];
s[i]=s[j];
s[j]=temp;
}
}
int string_len(char* str)
{
int x=0;
while(*str++){
x++;
}
return (x);
}
int main(int argc, char **argv)
{
char str[] = "this is very beautiful ";
printf("Length of string: %d\n",string_len(str));
printf("[%s]\n", reverse_word(str));
}
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
hi maximteo,
I just like to show you some strategies... I think with your understanding of C you should be able to implement it quite easily...
[this is very beautiful ] <-- find begin of left first word & right first word
[bhis is very teautiful ] <-- swap the characters while not ' '
[beis is very thautiful ]
[beas is very thiutiful ]
[beau is very thistiful ]
[beaut is very thisiful ] <-- space detected on left word, start shifting right
[beauti is very thisful ]
[beautif is very thisul ]
[beautifu is very thisl ]
[beautiful is very this ] <-- find begin and end of next left word & right word
[beautiful vs iery this ] <-- swap the characters while not ' '
[beautiful ve isry this ]
[beautiful ver isy this ] <-- space detected on left word start shifting right
[beautiful very is this ] <-- end
Another example...
[beautiful is very this ] <-- find begin of left first word & right first word
[teautiful is very bhis ] <-- swap the characters while not ' '
...
[thistiful is very beau ] <-- space detected on right word, start shifting left
[thisiful is very beaut ]
...
[this is very beautiful ] <-- find begin and end of next left word & right word
[this vs iery beautiful ] <-- swap the characters while not ' '
[this ve isry beautiful ] <-- space detected on left word, start shifting right
[this ver isy beautiful ]
[this very is beautiful ] <-- end
Cheers,
slyong
hey, pressed the submit by mistake. Writing again :)
Just a two step process:
This<space><space>is<space
1. Reverse the line
- the usual, use to counters (use pointers :)), one start of line, one end of line.
- start loop
- swap
- increment counter 1 and decrement counter 2 inside the loop.
- increment or decrement only if the character is not a <space>.
Step 1 would result in
doog<space><space>si<space
2. Now reverse the individual words.
Step 2 would result in
good<space><space>is<space
Shweta
I think the idea slyong suggests will produce an unnecessarily complicated result.
Break the problem down into parts! You will need to perform the following functions.
1. Find a complete word, starting at a specific position in a particular direction.
2. Swap two words.
Once you've achieved each of these, you're most of the way there.
Finding words is a sequence of loops which move a pointer back or forward (depending on the direction specified) until its passed a sequence of non-spaces then a sequence of spaces, stopping at the end or start of the string.
Swapping two words is just a matter of:
a. Copy the largest one out.
b. Copy the smallest into the gap left by the largest.
c. Shuffle the data so that the gap is now at the end of the smallest and is therefore big enough to take the largest.
d. Copy the largest in.
...short....muchlonger...
after a. and b.
...short....shortonger...
after c.
...short....s....short...
after d.
...muchlonger....short...
You will learn much more about programming by doing it the grown-up way of breaking the problem into smaller parts untill each is do-able than just achieving the output the customer(teacher) requested.
Paul
I think the major problem that the thing get a bit complicated is the restriction on dynamic memory allocation which I supposed, it also means that one is not allow to cheat by allocating a char myString[INT_MAX] or do something like char myString[string_len(str)].
This leave ones the only choice of allocating char and swapping and shiftting those characters around the original array. May be maximteo can englighten us on that part. If things like myString[INT_MAX] is allowed then Paul's idea of finding the words and swapping them word by word would be much simpler then implementing something like my idea.
Hi Slyong,
this was an interview question which i failed to answer =(
unfortunately myString[string_len(str)] is explictly allocating memory which is the restriction here too.
Slyong, I'm wondering when u mentioned "[beaut is very thisiful ] <-- space detected on left word, start shifting right"
wat do u mean by start shifting right ?
My understanding from what u said is to shift the index position of the rest of the chars ?
e.g {before shift} [beau is very thistiful ] current position of 'i' in 'is' = 7
{after shift} [beaut is very thisiful ] position of 'i' in 'is' = 8
so every character after 'beaut' gets shifted/pushed to the right shifting one index ?
if my understanding is correct, could u give a code sniplet to demonstrate how u'd do this ? (i'm just wondering if this is similar to insertion sort)
Hi maximteo,
just hack up something.. may not work properly.. but you can have a look. But sorry this is the maximum I would go for code sniplet. If you could understand shift_right, you could hack up shift_left quite easily... also I have not really done a proper testing on this.. so bugs here and there..
#define SWAP 0
#define SH_L 1
#define SH_R 2
int swap_string(char *str, int *l_pos, int *r_pos) {
char tmp;
while (str[*l_pos] != ' ' && str[*r_pos] != ' ') {
tmp = str[*l_pos];
str[*l_pos] = str[*r_pos];
str[*r_pos] = tmp;
(*l_pos)++; (*r_pos)++;
}
if (str[*l_pos] == ' ')
return SH_R; /* return what to do next */
else
return SH_L;
}
int shift_right(char *str, int *l_pos, int *r_pos) {
char tmp;
int i;
while (str[*r_pos] != ' ') {
tmp = str[*r_pos];
for (i = *r_pos; i > *l_pos; --i) {
str[i] = str[i - 1];
}
str[*l_pos] = tmp;
(*l_pos)++; (*r_pos)++;
}
return SWAP;
}
int main(int argc, char *argv[])
{
char str[] = "this is very beautiful ";
int cur_l_pos = 0, cur_r_pos = 24; /* I cheat a bit here... */
int next_op;
next_op = swap_string(str, &cur_l_pos, &cur_r_pos); /* next_op should tell me what to do next */
printf("SWAP %d:%d [%s]\n", cur_l_pos, cur_r_pos, str);
shift_right(str, &cur_l_pos, &cur_r_pos);
printf("SH_L %d:%d [%s]\n", cur_l_pos, cur_r_pos, str);
return EXIT_SUCCESS;
}
Hi maximteo,
Basically, you need to split up the input string into two different things:
1. The words themselves
2. The spacings
To reassemble the string in inverse order is relatively simple. Assuming your original string is consisting of W/S sequences (word/space):
original:
W1 S1 W2 S2 ... Sn-1 Wn
Split up:
Spaces: S1 S2 ... Sn-1 (there's always one spacing less)
Words: W1 W2 ... Wn
Reassemble:
Wn S1 Wn-1 S2 ... Sn-1 W1
...finished.
Start with the spacings. Since a space is a space, an array of space sizes is sufficient. Hint: check the isspace() function.
Then divide up the string words. Hint: check the strtok() function.
That should be enough to get you going.
Cheers!
Stefan
Business Accounts
Answer for Membership
by: PaulCaswellPosted on 2005-07-18 at 08:19:15ID: 14466967
maximteo,
Nice to see this old homework chestnut. Thankyou for showing it to us again!
This seems to me like a rather complicated way to achieve the required result. You are taking every space-delimited string in the string and reversing it, i.e. steps look like:
0. "this is very beautiful "
1. "lufituaeb yrev si siht "
2. "beautiful yrev si siht "
...
I would have thought you should follow the plan:
1. Find the starts of all the words in the string.
2. Swap all the words in the string.
Paul