Spread the love
Question:- Write a C program to reverse the words in a sentence in place !
To reverse the words in sentence in place, lets we understand the pseudo-code of program with example of sentence like “This is firmcodes.com”, So our output would be “firmcodes.com is This”.
Pseudocode:
Step 1 : Reverse the individual words
“sihT si moc.sedocmrif “
Step 2 : Reverse the whole string
“firmcodes.com is This”
#include<stdio.h> /* Driver Functions */ void ReverseString(char *s); void ReverseWords(char *begin, char *end); /* Main Method */ int main() { char s[]="This is www.firmcodes.com"; ReverseString(s); printf("%s",s); return 0; } /* Reverse the string */ void ReverseString(char *s) { char *start_word=s; char *traverse=s; /* Step 1 : Reverse the individual words */ while(*traverse) { if( start_word && (*(traverse+1)==' ') || (*(traverse+1)=='\0')) { ReverseWords(start_word,traverse); start_word=traverse+2; } traverse++; } /* Step 2 : Reverse the whole string */ ReverseWords(s,traverse-1); } /* Reverse individual words */ void ReverseWords(char *begin, char *end) { char temp; while(begin<end) { temp=*begin; *begin++=*end; *end--=temp; } }
Output
Suggested Reading
- Write your own trim() or squeeze() function to remove the spaces from a string
- search -for-a-substring/” target=”_blank” rel=”noopener” data-mce-href=”http://www.firmcodes.com/write-c-code-to-implement-the-strstr-function-to-search-for-a-substring/”>Write C code to implement the strstr() function to search for a substring
- Write a C program which does wildcard pattern matching algorithm
- structure padding and packing in c example