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
how we can make 3d venturing graphics on outer interface
Tell me what is null pointer in c?
What is the difference between Printf(..) and sprint(...) ?
How to create struct variables?
What is the use of a semicolon (;) at the end of every program statement?
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
What is s in c?
How many keywords are there in c?
What are the 3 types of structures?
Can you please compare array with pointer?
What does typeof return in c?
pierrot's divisor program using c or c++ code
How do I get an accurate error status return from system on ms-dos?
Why isnt any of this standardized in c?
What is use of integral promotions in c?