Reverse Words in a String

How to reverse words in a String?

In this problem, we have given an input string, we have to write a code to reverse the string word by word.

Example 1:

Input : “the carpet is green”

Output: “green is carpet the”

Example 2:

Input : ”  Java Ebook  “

Output: “Ebook Java”

Explanation: The reversed string should not contain leading or trailing spaces.

Example 3:

Input : “a good   example”

Output: “example good a”

Explanation: We have reduce multiple spaces between two words to a single space in the reversed string.

Note:

  • The Input string may contain leading or trailing spaces. However, the reversed string should not contain leading or trailing spaces.
  • We have to reduce multiple spaces between two words to a single space in the reversed string.

In this tutorial, I am going to discuss multiple approaches to solve a problem. Before seeing the solution, first try to solve this problem yourself.

Programming Video Tutorials

Programming Questions on Recursion

Reverse Words in a String using Two Pointers – Java Code

Let’s discuss how we can reverse a string without reversing the words in java using two pointers.

The idea here is to take two pointers. One is pointing at the beginning of the word and other pointer points to the end of the word. Traverse a string and when we encounter space, we insert them in a string builder at 0th offset.

Let’s solve this problem using in-built functions.

Reverse a String Word by Word – Java Code

The idea here is to split the string into an array of words. Then reverse this array and finally form a string from the array of words.

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.