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
Explain how can I make sure that my program is the only one accessing a file?
which of the following statement is wrong a) mes=123.56; b) con='T'*'A'; c) this='T'*20; d) 3+a=b;
Hi can anyone tell what is a start up code?
What is %g in c?
What are the string functions? List some string functions available in c.
Difference between goto, long jmp() and setjmp()?
What is scope rule of function in c?
Suggesting that there can be 62 seconds in a minute?
What is c preprocessor mean?
What are all different types of pointers in c?
Why doesnt that code work?
When should the volatile modifier be used?
Can a file other than a .h file be included with #include?
Why do we use return in c?
What is LINKED LIST? How can you access the last element in a linked list?