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, StringLogic 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.- Read a sentence from user in any variable say in string.
- Find a word from the end of string. Learn how to find words in a string.
- Append this word to reverseString (where reverseString holds the reverse order of words of the original string).
- 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
Original string
I love programming and learning at Codeforwin.
Reverse ordered words
Codeforwin. at learning and programming love I
Happy coding ;)