Reverse words in a given string
Here we can reverse word in a given string with the help of following program.
Example: If the given string is ''programming is my favorite subject" then the output should be ''subject favorite my is programming" i.e, nothing but
INPUT: programming is my favorite subject
OUTPUT:subject favorite my is programming
Program:
| #include <stdio.h> |
#include <conio.h>
#include <string.h>
int main()
{
char s[200];
int i, j, len, sWord, eWord;
printf("Enter the string : \n");
gets(s);
len = strlen(s);
eWord = length - 1;
printf("\nThe reverse order is: ");
for(i = len - 1; i >= 0; i--)
{
if(s[i] = = ' ' || i = = 0)
{
if(i = = 0)
{
sWord = 0;
}
else
{
sWord = i + 1;
}
for(j = sWord; j <= eWord; j++)
{
printf("%c ", s[j]);
}
eword = i - 1;
printf(" ");
}
}
return 0;
}
#include <string.h>
int main()
{
char s[200];
int i, j, len, sWord, eWord;
printf("Enter the string : \n");
gets(s);
len = strlen(s);
eWord = length - 1;
printf("\nThe reverse order is: ");
for(i = len - 1; i >= 0; i--)
{
if(s[i] = = ' ' || i = = 0)
{
if(i = = 0)
{
sWord = 0;
}
else
{
sWord = i + 1;
}
for(j = sWord; j <= eWord; j++)
{
printf("%c ", s[j]);
}
eword = i - 1;
printf(" ");
}
}
return 0;
}
Output:
| Enter the string : I love programming The reverse order is : programming love I |
Initially we include all the header files needed to write a program.The program starts from main(),
we can display the data with the help of prinf() and take the given input with the help to gets(s).The given string length is measured with the help of 'strlen' (this is a keyword to find the length of string ).The written logic executes and the output gets printed on the screen.

0 Comments