Reverse Words in a given string in Java

In this tutorial, we will see how to reverse a words of a given String. This is one of the most frequently asked questions in Coding Interviews. So, let us proceed with the question.


Example:
Input: "i love java language"
Ouput: "language java love i"

Approach:

We will use in-built java method i.e split() .The idea behind this is to split the given String into a temporary (temp) String array by using a delimiter which is space. In java, \\s means white-space character while \\s+ means one or more than white-space. We will use a ans="" i.e empty of String datatype which will be empty in starting.

So, here, splitted strings will be stored in temp[] array. Now, we will start a loop from last of temp[] array which will be executed until i>=0 and decrement i . Then we will append temp[i] into ans and add a space.(as shown below)
ans += temp[i]+" "

At last we have something to do, we need to remove leading and trailing spaces which can be achieved using trim() method in Java. Finally, we will return or print our answer with reversed words. Let us move to our code approach.



Code:
public class ReverseWords {
public static void main(String[] args) {
String s = "i love java language";

//ans will store the returned value from reverseWords()
String ans = reverseWords(s);

System.out.println(ans);
}

public static String reverseWords(String s) {
String ans = "";
String temp[] = s.split("\\s+");

for (int i = temp.length - 1; i >= 0; i--) {
ans += temp[i] + " ";
}
return ans.trim();
}
}

Output:

language java love i


Additional Information: This question is also asked in LeetCode problem number 151. And this approach passes all the TestCases.


Another Approach:

For making above solution better we can use StringBuilder class instead of String .

Below is the solution using StringBuilder class.



Code:
package String;

public class ReverseWords {
public static void main(String[] args) {
String s = "i love java language";

//ans will store the returned value from reverseWords()
String ans = reverseWords(s);

System.out.println(ans);
}

public static String reverseWords(String s) {
StringBuilder ans = new StringBuilder();
String []temp = s.split("\\s+");
for (int i = temp.length - 1; i >= 0; i--) {
ans.append(temp[i]).append(" ");
}

return ans.toString().trim();
}


}

Output:

language java love i


Also Read:

1 Comments

  1. Top 10 Casino Restaurants in Miami, FL - Goyang
    Find great 유흥가 deals at bet surface area Top 10 Casino 벳 삼육오 Restaurants in Miami, FL on Goyang Cafe. See reviews, 엠비 션 주소 photos 벳365코리아우회 & menus.

    ReplyDelete
Previous Post Next Post

Contact Form