C Programming - Reverse Words in a String (In-Place)
Another typical interview question!!Here is the solution that I could think off...Post your comments!!!
Solution:
#include < stdio.h >
#define SENT "Hello I am Here"
int reverse(char *string, char delimiter)
{
char *src, *dest,*temp=string;
while( *temp ) {
if (*temp == delimiter) {
temp++;
continue;
}
src=dest=temp;
while ( (*(dest+1) != delimiter) && ( *(dest+1) != '\0' ) ) dest++;
temp=dest+1;
while( dest > src ) {
char temp = *dest;
*dest-- = *src;
*src++=temp;
}
}
}
int main()
{
char name[] = SENT;
printf("Before Call: %s\n",name);
reverse(name,'\0'); /* Reverse Complete Sentence */
reverse(name,' '); /* Reverse Words */
printf("After Call: %s\n",name);
}
Labels: C
About this entry
You’re currently reading “
- Published:
- 6:29 am
- by -
4 Comments (Post a Comment)