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
What is the difference between array and structure in c?
Explain how do you view the path?
How will you divide two numbers in a MACRO?
How can you tell whether a program was compiled using c versus c++?
Why does this code crash?
What is the difference between ++a and a++?
Find the second largest element in an array with minimum no of comparisons and give the minimum no of comparisons needed on an array of size N to do the same.
Why doesnt this code work?
Is c is a high level language?
What are the differences between Structures and Arrays?
What is else if ladder?
Explain what will be the outcome of the following conditional statement if the value of variable s is 10?
Differentiate between new and malloc(), delete and free() ?
In c programming, explain how do you insert quote characters (? And ?) Into the output screen?
What is a header file?