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

how we can make 3d venturing graphics on outer interface

4028


Tell me what is null pointer in c?

621


What is the difference between Printf(..) and sprint(...) ?

798


How to create struct variables?

601


What is the use of a semicolon (;) at the end of every program statement?

788






in case any function return float value we must declare a) the function must be declared as 'float' in main() as well b) the function automatically returned float values c) function before declared 'float' keyword d) all the above

606


What is s in c?

626


How many keywords are there in c?

605


What are the 3 types of structures?

582


Can you please compare array with pointer?

625


What does typeof return in c?

648


pierrot's divisor program using c or c++ code

1738


How do I get an accurate error status return from system on ms-dos?

657


Why isnt any of this standardized in c?

645


What is use of integral promotions in c?

673