Trusted answers to developer questions

How to reverse the order of words in a sentence

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

If you are given the sentence “you shall not pass” and tasked with reversing the sentence’s word order; then the sentence becomes​ “pass not shall you”.

Consider the following illustration, which highlights one possible solution to this problem:

svg viewer

Implementation

One interesting thing about this problem is that all of its solutions are very language-dependent. Consider the implementations shown below:

C++

The following is an implementation of the method described above:

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str = "you shall not pass";
cout << "Original string: " << str << endl;
// Use the built-in reverse to get char-by-char reversal.
reverse(str.begin(), str.end());
string buffer = "";
string ans = "";
// This for loop then reverses each individual
// word in the string.
for (int i=0; i < str.length(); i++)
{
if (str[i] != ' ')
{
buffer += str[i];
}
else
{
reverse(buffer.begin(), buffer.end());
ans += buffer + " ";
buffer = "";
}
}
// Reversing the last word in the string outside the loop:
reverse(buffer.begin(), buffer.end());
ans += buffer;
cout << "Reversed string: " << ans << endl;
}

Python

Python has built-in functions to split the string, reverse the order of its words, and then join the words again. This implementation is shown below​:

string = 'you shall not pass'
split_str = string.split(' ') # split on spaces
reversed_str = reversed(split_str) # reverse words
final_str = ' '.join(reversed_str) # join the reversed words back to string
print("Reversed string: " , final_str)

Java

The solution in Java uses a built-in split function that is followed by the string being saved in reverse:

class ReverseWords {
public static void main(String args[]) {
String s[] = "you shall not pass".split(" ");
String ans = "";
for (int i = s.length - 1; i >= 0; i--) {
ans += s[i] + " ";
}
System.out.println("Reversed String: " + ans);
}
}

RELATED TAGS

reverse
order
words
sentence
algorithm
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?