Q:

Reverse words in a given string in c

0

This question generally asks by an interviewer, in this question you need to reverse the words of the string, for example, if your input string is “How are you”, the output will be “you are How”.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Steps to reverse words in a given string

  • First, you need to reverse the individual words, for example,
    If an input is “How are you”, the output will be “woH era uoy”.
  • Now, reverse the whole string and you will get “you are How”.

For the better understanding see the below code,

#include<stdio.h>
//function prototype to reverse
//the string from begin to end
void revString(char *pBegin, char *pEnd)
{
    char temp;
    while (pBegin < pEnd)
    {
        temp = *pBegin;
        *pBegin++ = *pEnd;
        *pEnd-- = temp;
    }
}
// Function to reverse words
void revWord(char *pString)
{
    // store the beginning address of word
    char *word_begin = NULL;
    //word_boundary is for word boundary
    char *word_boundary = pString; /* */
    //Loop to reverse the character of words
    while( *word_boundary )
    {
        //This condition is to make sure that
        //the string start with valid character
        if (( word_begin == NULL ) && (*word_boundary != ' ') )
        {
            word_begin = word_boundary;
        }
        if(word_begin && ((*(word_boundary+1) == ' ') || (*(word_boundary+1) == '\0')))
        {
            revString(word_begin, word_boundary);
            word_begin = NULL;
        }
        word_boundary++;
    }
    // reverse the whole string
    revString(pString, word_boundary-1);
}
int main()
{
    //source string
    char src[] = "How are you";
    //Reverse the word of the string
    revWord(src);
    //print the resultant string
    printf("Resultant string = %s", src);
    return 0;
}

Output: you are how

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Searching for a pattern in a given string... >>
<< Remove all duplicates from a given string in c...