Reverse words in a given string

Program : Let the input string is “I Am Happy”. The output should be “Happy Am I”

Concept:

  1. Reverse the individual words, we get the below string:  "I mA yppaH"
  2. Reverse the whole string from start to end and you get the desired output:            "Happy Am I"
#include<stdio.h>
#include<string.h>
#define BUFFER_SIZE 100

char buff[BUFFER_SIZE];
/* function prototype for utility function to
   reverse a string from begin to end  */

void reverse(char *begin, char *end);

/*Function to reverse words*/
void reverseWords(char *s)
{
        char *word_begin = s;
        char *temp = s; /* temp is for word boundary */
        /*STEP 1 of the above algorithm */
        while(*temp)
        {
                temp++;
                if (*temp == '\0')
                {
                        reverse(word_begin, temp-1);
                }
                else if(*temp == ' ')
                {
                        reverse(word_begin, temp-1);
                        word_begin = temp+1;
                }
        }

        /*STEP 2 of the above algorithm */
        reverse(s, temp-1);
}

/*Function to reverse any sequence starting with pointer
  begin and ending with pointer end  */

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

int main()
{
        char s[50];
        printf("Enter the string : ");
        fgets(s, sizeof(buff), stdin);
        char *temp = s;
        reverseWords(s);
        printf("The reverse of words in string is : %s", s);
        getchar();
        return 0;
}


Output : Enter the string : I Am Happy
The reverse of words in string is : Happy
 Am I


Remember : gets(str): This statement will give warning as : warning: the `gets' function is dangerous and should not be used.

In order to use gets safely, you have to know exactly how many characters that you will be reading so you can make your buffer large enough. You will only know that if you know exactly what data you will be reading.

Instead of using gets, you want to use fgets, which has the signature :

char* fgets(char *string, int length, FILE * stream);
(fgets, if it reads an entire line, will leave the '\n' in the string as in above output; you'll have to deal with that)

No comments:

Post a Comment