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 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
//Java Code public class ReverseWords { public static String reverseWords(String s) { StringBuilder result = new StringBuilder(); //Traverse a string for (int i = 0; i < s.length(); i++) { //If it is space then continue if(s.charAt(i) == ' ') continue; //Initialize with start pointer int start = i; //Run this loop until space is encountered while(i < s.length() && s.charAt(i) != ' ') i++; //If stringbuilder is empty, Add the first word at 0th offset if(result.length() == 0) result.insert(0, s.substring(start, i)); else result.insert(0, " ").insert(0, s.substring(start, i)); } return result.toString(); } public static void main(String[] args) { String str = " Three is word "; System.out.println(reverseWordsAppr(str)); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//Reverse a string word by word - Java Code public class ReverseWords { public static String reverseWords(String s) { /* If there are more than one spaces, it will not create multiple words. Basically taking care of multiple spaces between words.*/ String[] words = s.trim().split(" +"); Collections.reverse(Arrays.asList(words)); return String.join(" ", words); } public static void main(String[] args) { String str = " Three is word " System.out.println(reverseWordsAppr(str)); } } |