Java Program To Reverse The Words In A Sentence
I have written a program to reverse the words in a string. If i/p is 'The dog is chasing' then o/p should be 'chasing is dog The' public class String_reverse { public. Java Program to reverse each word in String. We can reverse each word of a string by the help of reverse(), split() and substring() methods. By using reverse() method of StringBuilder class, we can reverse given string. By the help of split(' s') method, we can get all words in an array.
I have the following code to reverse a string word by word, I have a question though, first could anyone point at how to make it better code? and second, how can I remove the space that I end up with at the beginning of the new string.
the phrase at the moment becomes:
olleh evarb wen dlrow
notice the space at the beginning of the new string.
TsundokuTsundoku34 Answers
Not using the split function the code would look like:
If str = 'The quick brown fox jumped over the lazy dog!' it will return it like 'dog! lazy the over jumped fox brown quick The' ...
My approach using StringUtils. In a unit test.
If you static import StringUtils, this could be inlined to:
LiggyLiggyFirst thing I would do is to separate code reversing the words form code reversing each word individually. This inner loop:
Would be a function/method call.
Also, to make your code more performant, instead of concatenating strings with the +
operator, I would use a string buffer class. Such as StringBuffer
or StringBuilder
.
First of all you should decouple it in three functions. The first breaking the big string in a list of strings using the space as delimiter, the second reversing one string without spaces, and the last concatenating strings.
When you do that it will be easier to locate what cause the space to appears. You can already see that in the current code but I am not going to tell you :D.
UmNyobeUmNyobeTry this. It takes into account punctuations and whitespace characters of any kind.
Another Solution. This solution is in-place.
Reverse words in a string (words are separated by one or more spaces), spaces can precede word(s) i.e space at begin of sentence, end etc... Solve it in-place.
}
Here's one thread also discussing this problem. I think one answer using split with regex is very clever.
The answer to your removal of the starting space character is easy, just
String.trim()
returns a copy of the string, with leading and trailing whitespace omitted (as copied from the Javadoc documentation).
For your overall problem, I made this sample up:
and the output is:
If you want to be more inclusive of any white space character, e.g., tab character, line break, form feed, then change the split()
argument to split('s')
as s
is the regex character class which embodies [ trnf]. Notice how you must escape the backslash character in your Java string representation of a regular expression (which is what the split method expects).
Here is a coding technique using the popular split
() function, which is available in all major languages, the Java toCharArray
(), good for full control of characters in a string form, and the Java StringBuilder
class for performance sake (available in C# too).
I think the code is easier to understand when compared to the other posted answers
Reminder of the requirements posted by the author.
Sample input: 'Hello World'
Output: 'olleH dlroW'
I'm fairly new to Java myself, and I expect I've been beaten to the punch but I thought I'd give it a go anyway. You could solve the extra whitespace problem by building up the string with the assumption that you will delete the unwanted extra space at the end. If performance is a consideration then you might want to rethink this!
Edit: Note that my solution (now) handles leading and trailing whitespace.
So, I'm assuming that you're learning/practicing java and that there is a high risk of homework question... This means that you'll either love or hate this answer...
If you take a look at the String object source code you'll find something like this inside:
private final char value[]; //this stores the String's characters
The first step is to get that value[] with:
Note the function implementation (from openjdk-7), it returns a copy of the array and not the original one because String objects are immutable.
Now that we have myChars
we can play around with it and get to the result in linear time O(n)!
And here is the reverse function:
Now just for fun you might want to try to get to the following output instead and maybe you'll get this exact question from some interviewer that ran out of fantasy one day:
world new brave hello
The following should do it in O(n) without any expensive array copying or re-structuring the character array length. Takes care of multiple preceding, in-between and trailing whitespaces.
Satadru BiswasSatadru BiswasTake a String and using Stack
methods with StringTokenizer
Object and with its methods we can cut the String into the piece of Words using delimeter
. By the Stack Natural feature insert (push)
all the words into the Satck and Remove (pop)
all the words from Stack. then print of those all.
Here we can take the String s='hello brave new world'
If you are using any package with your own then check the Output of above program.
Mdhar9eMdhar9eI think my code below is more efficient than any code available here:
}
Example: 'hello world'
will become : 'dlrow olleho'
AbhilashaI tried to do without split function. Instead using substring and for loop.
Input: Behind you is a symbol of oppressionOutput: oppression of symbol a is you Behind
Input: ThisIsAllOneWordOutput: ThisIsAllOneWord
Not the answer you're looking for? Browse other questions tagged javastring or ask your own question.
I need a little help. I found a question like 'Write a Java program that will reverse each word of user given string without altering their position and using any built in function.'
I solved a code for reversing the whole sentence, but I don't know how to solve this one. Please help me...
Micho23 Answers
1) Split your sentence (using split(), this will return an array, say words[])
2) Reverse each word in the array words[].
3) Reconstruct your sentence from the array words[].
Here is simple code that implements @Maximin's answer.
The reversed strings could also be placed into their own array by declaring String[] reverse = new String[words.length];
, allowing you the option to reconstruct the sentence or format output as desired.
split the string using space and then loop through each element of String array and reverse it:
C Program To Reverse The Words In A String
public class StringReverse {
}
I too tried this.Since I am learning java i tried this code in simple way.If i did any mistake in code or logic please correct me.Thank you....;
class Program { static void Main(string[] args) { int i = 0,j=0; string test = 'Hello Sir I am good'; StringBuilder sb = new StringBuilder(); char[] str = test.ToCharArray(); char[] revstr; while (i < str.Length) i++; i--; for (int k = i; k >= j;) {
i also faced a similar question but didn't clear the round because my approach was too complex for the person evaluating my answer, i am sharing it here, hope it helps someone.
Now you have your words stored in the array 'words' just reverse them.
Sujal MandalSujal MandalSimple Solution: First we enter a enter a string through a scannerThen we split it by spaces. Then we reverse it using a for loop and output it.
Please go through my approach.It will provide you correct output:-
this function will take a string as input and would reverse the string.
Java Program To Reverse Individual Words In A Sentence
input: Hello i am ashish
output: ashish am i Hello