C program to reverse order of words in a string

Write a C program to input any string from user and reverse the order of words. How to reverse the order of words in a given string using C programming. Logic to reverse the order of words in a sentence using C program.

Example:
Input string : I love programming and learning at Codeforwin.
Output string: Codeforwin. at learning and programming love I

Required knowledge

Basic C programming, If else, Loop, String

Logic to reverse the order of words in a given string

There are many logic's to reverse the order of words. Below is the simplest approach I am using to reverse the order.
  1. Read a sentence from user in any variable say in string.
  2. Find a word from the end of string. Learn how to find words in a string.
  3. Append this word to reverseString (where reverseString holds the reverse order of words of the original string).
  4. Repeat step 2-3 till the beginning of string.


Program to reverse the order of words in a given string

/**
 * C program to reverse order of words in a string
 */

#include <stdio.h>
#include <string.h>

int main()
{
    char string[100], reverse[100];
    int len, i, index, wordStart, wordEnd;

    printf("Enter any string: ");
    gets(string);

    len   = strlen(string);
    index = 0;

    // Start checking of words from the end of string
    wordStart = len - 1;
    wordEnd  = len - 1;

    while(wordStart > 0)
    {
        // If a word is found
        if(string[wordStart] == ' ')
        {
            // Add the word to the reverse string
            i = wordStart + 1;
            while(i <= wordEnd)
            {
                reverse[index] = string[i];

                i++;
                index++;
            }
            reverse[index++] = ' ';

            wordEnd = wordStart - 1;
        }

        wordStart--;
    }

    // Finally add the last word
    for(i=0; i<=wordEnd; i++)
    {
        reverse[index] = string[i];
        index++;
    }
    reverse[index] = '\0'; // Adds a NULL character at the end of string

    printf("Original string \n%s\n\n", string);
    printf("Reverse ordered words \n%s", reverse);


    return 0;
}


Output
Enter any string: I love programming and learning at Codeforwin.
Original string
I love programming and learning at Codeforwin.

Reverse ordered words
Codeforwin. at learning and programming love I

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment