C Program to Word Reverse a String

Write a program to word reverse a string.

Example :
Input :
this is a test sentence to test this has 13 words for word reversal
Output :
reversal word for words 13 has this test to sentence test a is this

Constraints:
The string will have a maximum of 500 characters.

Code:

#include <stdio.h>
#include <string.h>
 
int main()
{
  	char str[500];
  	int i, len;
 
    scanf("%[^\n]",str);  
  	
  	len = strlen(str);
  	for(i = len - 1; i >= 0; i--)
	{
		if(str[i] == ' ')
		{
			str[i] = '\0';
			printf("%s ", &(str[i]) + 1);	
		} 
	}
	printf("%s", str);
	
  	return 0;
}
Code language: C/AL (cal)

Leave a Comment