# 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 = “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++

 `// CPP program to reverse a string ` `#include ` `using` `namespace` `std; ` ` `  `// Function to reverse words*/ ` `void` `reverseWords(string& s) ` `{ ` `    ``// Reversing individual words as ` `    ``// explained in the first step ` ` `  `    ``int` `start = 0; ` `    ``for` `(``int` `end = 0; end < s.length(); end++) { ` ` `  `        ``// If we see a space, we reverse the previous  ` `        ``// word (word between the indexes start and end-1 ` `        ``// i.e., s[start..end-1] ` `        ``if` `(s[end] == ``' '``) { ` `            ``reverse(s.begin() + start, s.begin() + end); ` `            ``start = end + 1; ` `        ``} ` `    ``} ` ` `  `    ``// Reverse the last word ` `    ``reverse(s.begin() + start, s.end()); ` ` `  `    ``// Reverse the entire string ` `    ``reverse(s.begin(), s.end()); ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``string s = ``"i like this program very much"``; ` `    ``reverseWords(s); ` `    ``cout << s; ` `    ``return` `0; ` `} `

## C

 `// C program to reverse a string ` `#include ` ` `  `// 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
```

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 space in between. Thanks to rka143 for providing this version.

 `void` `reverseWords(``char``* s) ` `{ ` `    ``char``* word_begin = NULL; ` `    ``char``* temp = s; ``/* temp is for word boundary */` ` `  `    ``/*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) == ``'\0'``))) { ` `            ``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)
we can do the above task by splitting and saving the string in reverse manner.

## Java

 `// Java program to reverse a string ` `// s = input() ` `public` `class` `ReverseWords { ` ` `  `    ``public` `static` `void` `main(String[] args) ` `    ``{ ` `        ``String s[] = ``"i like this program very much"``.split(``" "``); ` `        ``String ans = ``""``; ` `        ``for` `(``int` `i = s.length - ``1``; i >= ``0``; i--) { ` `            ``ans += s[i] + ``" "``; ` `        ``} ` `        ``System.out.println(``"Reversed String:"``); ` `        ``System.out.println(ans.substring(``0``, ans.length() - ``1``)); ` `    ``} ` `} `

## C#

 `// C# program to reverse a string ` `// s = input() ` ` `  `using` `System; ` `public` `class` `ReverseWords { ` ` `  `    ``public` `static` `void` `Main() ` `    ``{ ` `        ``string``[] s = ``"i like this program very much"``.Split(``' '``); ` `        ``string` `ans = ``""``; ` `        ``for` `(``int` `i = s.Length - 1; i >= 0; i--) { ` `            ``ans += s[i] + ``" "``; ` `        ``} ` `        ``Console.Write(``"Reversed String:\n"``); ` `        ``Console.Write(ans.Substring(0, ans.Length - 1)); ` `    ``} ` `} `

## Python3

 `# Python3 program to reverse a string ` `# s = input() ` `s ``=` `"i like this program very much"` `words ``=` `s.split(``' '``) ` `string ``=``[] ` `for` `word ``in` `words: ` `    ``string.insert(``0``, word) ` ` `  `print``(``"Reversed String:"``) ` `print``(``" "``.join(string)) ` ` `  `# Solution proposed bu Uttam `

Output:

```Reversed String:
much very program this like i
```

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Article Tags :

32

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.