Reverse Each word in a string or sentence Interview Question














































Reverse Each word in a string or sentence Interview Question



Reverse Each word in a string or sentence Interview Question

Given a String in which we have to reverse each word of that string and print the sentence.

Example 1:

Input: "This is my resume"
output: "sihT si ym emusem"

Example 2:

Input: "Internship at cpp secrets"
output: "pihsnretnI ta ppc sterces"

Method 1

def reverseWordSentence(Sentence):
# Splitting the Sentence into list of words.
words = Sentence.split(" ")

# Reversing each word and creating
# a new list of words
# List Comprehension Technique
newWords = [word[::-1] for word in words]

# Joining the new list of words
# to for a new Sentence
newSentence = " ".join(newWords)

return newSentence


METHOD 2(Using Inbuilt Function

def reverseWordSentence(Sentence):
# All in One line
return ' '.join(word[::-1] for word in Sentence.split(" "))


Method 3

def reverserWords(string):
st = list()

# Traverse given string and push all characters
# to stack until we see a space.
for i in range(len(string)):
if string[i] != " ":
st.append(string[i])

# When we see a space, we print
# contents of stack
else:
while len(st) > 0:
print(st[-1], end="")
st.pop()
print(end=" ")

# Since there may not be space after
# last word.
while len(st) > 0:
print(st[-1], end="")
st.pop()

This Article Is Written By Rohit Bansal

Comments