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 goto?
why return type of main is not necessary in linux
What are runtime error?
what are the program that using a two dimensional array that list the odd numbers and even numbers separately in a given 10 inputs values
Write a Program to accept different goods with the number, price and date of purchase and display them
Write a program to identify if a given binary tree is balanced or not.
What is variable in c example?
Why do we use main function?
what do u mean by Direct access files? then can u explain about Direct Access Files?
Where are local variables stored in c?
Do array subscripts always start with zero?
What is zero based addressing?
What is a void pointer in c?
How do you list a file’s date and time?
Can a function argument have default value?