Refer following program to reverse the order of words in a string:
Code:
#include <stdio.h>
#include <string.h>
char string[20];
void strrev(char *start, char* end)
{
char temp;
if( !start || !end ) //null pointer check
return;
for(; start<=end; start++, end-- )
{
temp = *start;
*start = *end;
*end = temp;
}
}
int main()
{
char* tempstr = string;
char* tempstr2;
printf("Enter the string with words: ");
scanf("%[^n]s", string);
strrev( tempstr, tempstr+strlen(tempstr)-1 );
printf( "%sn", tempstr, string );
while( *tempstr!=0 )
{
tempstr2 = tempstr;
while( tempstr2 && (*tempstr2!=' ' && *tempstr2!=0) )
tempstr2++;
strrev( tempstr, tempstr2-1 );
tempstr = tempstr2+1;
}
printf( "%sn", string );
} I have tried the given code but it didn’t solve my problem. Please try to provide some other solution.
Bookmarks