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


Please Help Members By Posting Answers For Below Questions

Explain goto?

907


why return type of main is not necessary in linux

1873


What are runtime error?

839


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

1448


Write a Program to accept different goods with the number, price and date of purchase and display them

5860


Write a program to identify if a given binary tree is balanced or not.

902


What is variable in c example?

800


Why do we use main function?

886


what do u mean by Direct access files? then can u explain about Direct Access Files?

1834


Where are local variables stored in c?

758


Do array subscripts always start with zero?

999


What is zero based addressing?

914


What is a void pointer in c?

827


How do you list a file’s date and time?

814


Can a function argument have default value?

899