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
Is using exit() the same as using return?
What could possibly be the problem if a valid function name such as tolower() is being reported by the C compiler as undefined?
difference between Low, Middle, High Level languages in c ?
Discuss the function of conditional operator, size of operator and comma operator with examples.
Distinguish between actual and formal arguments.
number of times a digit is present in a number
What is sorting in c plus plus?
What are the advantages of the functions?
Write a program to reverse a linked list in c.
Why we use stdio h in c?
What language is lisp written in?
What's the total generic pointer type?
What are the advantages of union?
What do you understand by normalization of pointers?
What is the correct code to have following output in c using nested for loop?