Tutorials  Articles  Notifications  Login  Signup


HS

Harsh Shukla

Intern at Microsoft Sept. 3, 2020, 1:49 p.m. ⋅ 1355 views

Reverse words in a given string


Let's take a string s,  we want to reverse its words. For example - 

Sample input 1

Hello HackersFriend

Sample output 1

HackersFriend Hello

 

Solution

Easiest way to implement it would be to split the string s and the reverse it. Here is implementation of this approach.

# Python3 program to reverse words of a string 
# s = input() 

s = "Hello HackersFriend"
words = s.split(' ') 

string =[] 

for word in words: 
	string.insert(0, word) 

print("Reversed String: ", end= '') 
print(" ".join(string))

 

HackersFriend Hello

 

You can also implement it using stacks. Initially you can push every word from beginning into stack then pop it out and print it. The reason why this approach would work is because, stack in LIFO (Last In First Out) Data structure, hence the word, which we will push at end would come first and so on.

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account