Program to reverse the words of string

This program is little bit modification to the previous post program.After reversing the letters of each words in a string when we call again the reverse function the words get reversed of the string.


#include<stdio.h>
#include<conio.h>
void reverse(char *start, char *end);
void reversethewords(char *s)
{
  char *wordbegin = s;      //wordbegin and t are two pointer to the first character of string s
  char *t = s;            
  while( *t)
  {
    t++;
    if (*t == '\0')            // if reached at the end of the string reverse(swap) the first character and last and
    {                                                                                                                            so on.
      reverse(wordbegin, t-1);
    }
    else if(*t == ' ')        // if encountered with space then reverse and make wordbegin=t+1 for the
    {                                                                                                                            next word
      reverse(wordbegin, t-1);
      wordbegin = t+1;
    }
  }
 reverse(s, t-1);       //Again calling reverse function to reverse the words
}

void reverse(char *start, char *end)
{
  char temp;
  while (start < end)
  {
    temp = *start;
    *start++ = *end;
    *end-- = temp;
  }
}

int main()
{
  char s[] = "I love this blog";
  reversethewords(s);
  printf("%s", s);
getch();
}

Output-"blog this love I"

Comments

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Number series arrangement puzzles