Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
C# Program To Reverse Words In A Given String
Next article icon

C Program To Reverse Words In A Given String

Last Updated : 02 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”

reverse-words

Examples: 

Input: s = “geeks quiz practice code” 
Output: s = “code practice quiz geeks”

Input: s = “getting good at coding needs a lot of practice” 
Output: s = “practice of lot a needs coding at good getting”

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

Algorithm:  

  • Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
  • Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.

Below is the implementation of the above approach: 

C

// C program to reverse a string
#include <stdio.h>
 
// Function to reverse any sequence
// starting with pointer begin and
// ending with pointer end
void reverse(char* begin,char* end)
{
    char temp;
    while (begin < end)
    {
        temp = *begin;
        *begin++ = *end;
        *end-- = temp;
    }
}
 
// Function to reverse words
void reverseWords(char* s)
{
    char* word_begin = s;
 
    // Word boundary
    char* temp = s;
 
    // Reversing individual words as
    // explained in the first step
    while (*temp)
    {
        temp++;
        if (*temp =='\0')
        {
            reverse(word_begin,temp - 1);
        }
        else if (*temp == ' ')
        {
            reverse(word_begin,temp - 1);
            word_begin = temp + 1;
        }
    }
 
    // Reverse the entire string
    reverse(s, temp - 1);
}
 
// Driver Code
int main()
{
    char s[] =
    "i like this program very much";
    char* temp = s;
    reverseWords(s);
    printf("%s", s);
    return 0;
}
                      
                       

Output
much very program this like i

Time Complexity: O(n)
Auxiliary Space: O(n) 

The above code doesn’t handle the cases when the string starts with space. The following version handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple spaces in between. Thanks to rka143 for providing this version. 

C

// C program to implement
// the above approach
void reverseWords(char* s)
{
    char* word_begin = NULL;
   
    // temp is for word boundary
    char* temp = s;
 
    // STEP 1 of the above algorithm
    while (*temp)
    {
        /*This condition is to make sure
          that the string start with valid
          character (not space) only*/
        if ((word_begin == NULL) &&
            (*temp != ' '))
        {
            word_begin = temp;
        }
        if (word_begin &&
           ((*(temp + 1) == ' ') ||
            (*(temp + 1) == '')))
        {
            reverse(word_begin, temp);
            word_begin = NULL;
        }
        temp++;
    // End of while
    }
 
    // STEP 2 of the above algorithm
    reverse(s, temp - 1);
}
                      
                       

Time Complexity: O(n) 
Another Approach:

Please refer complete article on Reverse words in a given string for more details!



Next Article
C# Program To Reverse Words In A Given String
author
kartik
Improve
Article Tags :
  • C Programs
  • DSA
  • Strings
  • Accolite
  • Adobe
  • Amazon
  • CBSE - Class 11
  • Cisco
  • Goldman Sachs
  • MakeMyTrip
  • MAQ Software
  • Microsoft
  • Morgan Stanley
  • Paytm
  • Payu
  • Reverse
  • SAP Labs
  • school-programming
  • Wipro
  • Zoho
Practice Tags :
  • Accolite
  • Adobe
  • Amazon
  • Cisco
  • Goldman Sachs
  • MakeMyTrip
  • MAQ Software
  • Microsoft
  • Morgan Stanley
  • Paytm
  • Payu
  • SAP Labs
  • Wipro
  • Zoho
  • Reverse
  • Strings

Similar Reads

  • C# Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "p
    4 min read
  • C Program to Reverse a String Using Recursion
    Reversing a string means changing the order of characters in the string so that the last character becomes the first character of the string. In this article, we will learn how to reverse a string using recursion in a C program. The string can be reversed by using two pointers: one at the start and
    1 min read
  • How to Reverse a String in C?
    In C, a string is a sequence of characters terminated by a null character (\0). Reversing a string means changing the order of the characters such that the characters at the end of the string come at the start and vice versa. In this article, we will learn how to reverse a string in C. Example: Inpu
    2 min read
  • C Program to Traverse an Array in Reverse
    Write a C program to traverse a given array in reverse order that contains N elements. Examples Input: arr[] = {2, -1, 5, 6, 0, -3}Output: -3 0 6 5 -1 2 Input: arr[] = {4, 0, -2, -9, -7, 1}Output: 1 -7 -9 -2 0 4 Different Ways to Traverse an Array in Reverse Order in CWe can traverse/print the array
    2 min read
  • C Program to Replace a Word in a Text By Another Given Word
    Given three strings 'str', 'oldW' and 'newW'. The task is find all occurrences of the word 'oldW' and replace then with word 'newW'. Examples: Input : str[] = "xxforxx xx for xx", oldW[] = "xx", newW[] = "geeks" Output : geeksforgeeks geeks for geeksRecommended: Please solve it on “PRACTICE ” first,
    3 min read
  • C Program To Print Reverse Floyd's Pattern
    The Reverse Floyd's Triangle Pattern prints numbers or characters in reverse order, starting with the largest at the top and decreasing as the rows progress. Basically, it is Floyd's triangle that starts with the largest number and ends with 1. In this article, we will learn how to print the Reverse
    2 min read
  • C Program to Find the Length of a String
    The length of a string is the number of characters in it without including the null character (‘\0’). In this article, we will learn how to find the length of a string in C. The easiest way to find the string length is by using strlen() function from the C strings library. Let's take a look at an ex
    2 min read
  • Reverse Number Program in C
    The reverse of a number means reversing the order of digits of a number. In this article, we will learn how to reverse the digits of a number in C programming language. For example, if number num = 12548, the reverse of number num is 84521. Algorithm to Reverse an IntegerInput: num (1) Initialize re
    2 min read
  • C Program to Sort a String of Characters
    Sorting a string of characters refers to the process of rearranging all the characters in the given order. In this article, we will learn how to sort a string of characters using the C program. The most straightforward method to sort a string of characters is by using the qsort() function. Let's tak
    3 min read
  • C Program to print all permutations of a given string
    A permutation also called an "arrangement number" or "order," is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.  Source: Mathword(http://mathworld.wolfram.com/Permutation.html) Below are the permutations o
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences