How to Reverse words in String Java? [Solution] (original) (raw)
Hello guys, if you are wondering how to reverse words in a given String in Java then you have come to the right place. Earlier, I have shared 75 Programming interview questions and In this Java Coding tutorial, you will learn how to reverse words in String. It's also one of the popular coding questions, so you will also learn how to take a requirement, how to fill gaps in the requirement by asking the right question. A String is nothing but a sentence, which may contain multiple works, or just contain a single word or it may be empty. Your program must produce a String that contains the word in reverse order, for example, if the given input is "Java is Great" then your program should return "Great is Java".
Now, if you are a good programmer then you should have some right questions for the Interviewer. Never assume you know everything, even if it looks like a simple problem.
Always remember "Devil is in detail". Also asking a question, not only fill the gaps in requirement but also help you to make an impression.
One question the candidate should definitely ask is, what constitutes a word here? For the purpose of this program, the word is nothing but a sequence of non-space characters.
Another good question you can ask to Interview is about input like is it possible for input string to contain leading or trailing spaces?
Yes, it's possible. However, your reversed string should not any contain leading or trailing spaces.
One more important question for the Interviewer is about spacing between words, is it possible to have multiple spaces between two words? Yes, it could be possible but you can reduce them to a single space in the reversed string.
Reversing the order of words in a Sentence in Java - Solution
Here is our Java solution to this problem. It's simple and straightforward. In this code example, I have shown two ways to reverse words in a String, first one is using, Java's regular expression support to split the string into spaces and then using the reverse() method of Collections utility class.
Once you split the String using regex "\\s", it will return you an array of words. It will also handle words separated by multiple spaces, so you don't need to worry.
Once you got the array, you can create an ArrayList from an array, and then you are eligible to use Collections.reverse() method.
This will reverse your ArrayList and you will have all the words in reverse order, now all you need to do is concatenate multiple String by iterating over ArrayList.
I have used StringBuilder for concatenating String here. Also make sure to specify size, because resizing of StringBuilder is costly as it involves the creation of a new array and copying content from the old to the new array.
As I said earlier, for more coding problems from programming interviews, you can also check the Grokking the Coding Interview: Patterns for Coding Questions, one of the best resources to learn essential coding patterns like sliding window, merge interval, fast and slow pointers, etc which can be used to solve 100+ Leetcode problems.
The second method to reverse words in a given string is, even more, easier, instead of using the Collections.reverse() method, I have just used the traditional for loop and started looping over array from the end and performing String concatenation.
This way, you even don't need to convert your String array to ArrayList of String. This solution is more memory efficient and faster than the previous one.
import java.util.Arrays; import java.util.Collections; import java.util.List;
/**
- Java Program to reverse words in String. There are multiple way to solve this
- problem. you can either use any collection class like List and reverse the
- List and later create reverse String by joining individual words.
- @author Javin Paul */ public class Testing {
public static void main(String args[]) {
}
/*
Method to reverse words in String in Java */ public static String reverseWords(String sentence) { List< String> words = Arrays.asList(sentence.split("\s")); Collections.reverse(words); StringBuilder sb = new StringBuilder(sentence.length());
for (int i = words.size() - 1; i >= 0; i--) { sb.append(words.get(i)); sb.append(' '); }
return sb.toString().trim();
}
public static String reverseString(String line) { if (line.trim().isEmpty()) { return line; }
StringBuilder reverse = new StringBuilder();
String[] sa = line.trim().split("\\s");
for (int i = sa.length - 1; i >= 0; i--) {
reverse.append(sa[i]);
reverse.append(' ');
}
return reverse.toString().trim();
} } }
Sometimes Interviewer may ask you to solve this problem without using the Java Collection framework because it obviously makes the task a lot easier. So it's also good to prepare a solution based upon pure programming logic.
If you know how to reverse an array in Java, then you have an advantage because String is nothing but a character array, but the tricky part is you don't need to reverse array but to reverse words.
And, If you are preparing for a programming interview, I also suggest taking a look at Cracking the Coding Interview: 189 Programming Questions and Solutions, one of the best books to prepare for programming job interviews. You will find several such problems and great explanations in this book.
That's all about how to reverse words in a String sentence in Java. You have learned two ways to reverse the order of words. You have also learned how to split String using regex, which is an important skill for Java programmers and you have also learned a good utility method to reverse any Collection in Java. It's good to practice this kind of coding problem both to learn Java and to improve your programming and coding skills.
Other Java Coding Problems You may like to Practice
- 100+ Data Structure and Algorithms Problems (solutions)
- Write a program to print the highest frequency word from a text file? (solution)
- How to find if given String is a palindrome in Java? (solution)
- How to calculate factorial using recursion and iteration? (solution)
- How to reverse an integer variable in Java? (solution)
- Write code to implement Bubble sort algorithm in Java? (code)
- How to find the highest and lowest number from the int array? (answer)
- How do you swap two integers without using a temporary variable? (solution)
- Top 10 Programming problems from Java Interviews? (article)
- Write a program to check if a number is the power of two or not? (solution)
- How to check if a year is a leap year in Java? (answer)
- How to check if a given number is prime or not? (solution)
- How to reverse String in Java without using StringBuffer? (solution)
- Write code to implement Quicksort algorithm in Java? (algorithm)
- How to find a missing number in a sorted array? (solution)
- Write a program to code insertion sort algorithm in Java (program)
Thanks for reading this article so far. If you like this String based coding problem and solution then please share it with your friends and colleagues. If you have any doubt then please drop a note.
P. S. - If you are a beginner and looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free and all you need to do is create a free Udemy account to enroll in this course.