Given an array of characters which form a sentence of
words, give an efficient algorithm to reverse the order of
the words (not characters) in it?

Answer Posted / abdur rab

#include <stdio.h>

void reverse_string ( char* cp_string, int start, int end )
{
if ( cp_string && ( start < end ) ) {
*( cp_string + start ) ^= *( cp_string +
end )
^= *( cp_string + start ) ^= *(
cp_string + end );
reverse_string ( cp_string, ++start, --
end );
}
}


int main ( int argc, char* argv [] )
{
char ca_array [12]={"Hello World"};
char* cp_ptr = NULL;
char* cp_ptr_temp = NULL;

printf ( "\n Before Reverse :%s", ca_array );

reverse_string ( ca_array, 0, strlen ( ca_array ) -
1 );

cp_ptr_temp = cp_ptr = ca_array;
while ( NULL != ( cp_ptr_temp = (char*) strchr (
cp_ptr_temp, ' ' ) ) ) {
reverse_string ( cp_ptr, 0, ( cp_ptr_temp -
cp_ptr ) - 1 );
cp_ptr = ++cp_ptr_temp;
}
// change the final word
reverse_string ( cp_ptr, 0,
( ( strlen ( ca_array ) - 1 ) - (
cp_ptr - ca_array ) ) );

printf ( "\n After Reverse by Words :%s",
ca_array );
return ( 0 );
}

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain how can I make sure that my program is the only one accessing a file?

633


which of the following statement is wrong a) mes=123.56; b) con='T'*'A'; c) this='T'*20; d) 3+a=b;

2416


Hi can anyone tell what is a start up code?

1619


What is %g in c?

626


What are the string functions? List some string functions available in c.

609






Difference between goto, long jmp() and setjmp()?

712


What is scope rule of function in c?

555


Suggesting that there can be 62 seconds in a minute?

602


What is c preprocessor mean?

797


What are all different types of pointers in c?

581


Why doesnt that code work?

604


When should the volatile modifier be used?

689


Can a file other than a .h file be included with #include?

688


Why do we use return in c?

572


What is LINKED LIST? How can you access the last element in a linked list?

636