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
Can include files be nested? How many levels deep can include files be nested?
Do character constants represent numerical values?
Describe how arrays can be passed to a user defined function
Write a program to generate random numbers in c?
Are there constructors in c?
What is meant by realloc()?
What is the difference between union and structure in c?
How do I use strcmp?
What does sizeof int return?
find the value of y y = 1.5x+3 for x<=2 y = 2x+5 for x>2
What is the newline escape sequence?
exit () is used to a) exit () terminates the execution of the program itself b) exit () terminates the execution of the loop c) exit () terminates the execution of the block d) none of the above
Why void is used in c?
How do we open a binary file in Read/Write mode in C?
What is the general form of #line preprocessor?