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.

Active1 year, 11 months ago

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.

TsundokuTsundoku
3,74426 gold badges79 silver badges124 bronze badges

34 Answers

12 next

Not using the split function the code would look like:

CalifaxCalifax

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' ...

girmangirman
DawoodDawood
2,8432 gold badges14 silver badges26 bronze badges

My approach using StringUtils. In a unit test.

If you static import StringUtils, this could be inlined to:

LiggyLiggy
7762 gold badges9 silver badges19 bronze badges

First 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.

Pablo Santa CruzPablo Santa Cruz
141k29 gold badges206 silver badges257 bronze badges

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.

UmNyobeUmNyobe
18.7k8 gold badges42 silver badges77 bronze badges
Abhijeet RastogiAbhijeet Rastogi
10.4k19 gold badges66 silver badges110 bronze badges
user973999

Try this. It takes into account punctuations and whitespace characters of any kind.

eternaln00beternaln00b
Jacob StevensJacob Stevens
MikroDel
5,4386 gold badges32 silver badges66 bronze badges
Ajay KumarAjay Kumar
Pani DhakshnamurthyPani Dhakshnamurthy

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.

}

user2296600user2296600

Here's one thread also discussing this problem. I think one answer using split with regex is very clever.

Community
Charles XuCharles Xu

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).

Jim DaehnJim Daehn
Muhammad AbbasMuhammad Abbas

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'

The Original AndroidThe Original Android
4,9963 gold badges18 silver badges29 bronze badges
jusiojusio
9,2151 gold badge35 silver badges53 bronze badges

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.

mleonardmleonard

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

GevorgGevorg
9,58014 gold badges66 silver badges117 bronze badges

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 Biswas
1,3261 gold badge11 silver badges21 bronze badges

Take 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.

Mdhar9eMdhar9e
8003 gold badges18 silver badges43 bronze badges
user492883user492883
Andrew Barber
34.6k14 gold badges80 silver badges109 bronze badges
AskerAsker

I think my code below is more efficient than any code available here:

}

Example: 'hello world'

will become : 'dlrow olleho'

Abhilasha
7601 gold badge14 silver badges35 bronze badges
driven_spiderdriven_spider
vanduc1102vanduc1102
2,4671 gold badge26 silver badges26 bronze badges

I 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

enthiranenthiran
Kcvin
4,4141 gold badge26 silver badges50 bronze badges
ShikhaShikha
SaswataSaswata
beresfordt
4,0897 gold badges28 silver badges39 bronze badges
HaSnen TaiHaSnen Tai
4421 gold badge5 silver badges15 bronze badges

Not the answer you're looking for? Browse other questions tagged javastring or ask your own question.

Active1 year ago

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...

Micho
3,46911 gold badges31 silver badges39 bronze badges
debanjandebanjan

23 Answers

Java

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[].

MaximinMaximin
Umang MehtaUmang Mehta

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.

voidHeadvoidHeadWords
7261 gold badge6 silver badges19 bronze badges

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 {

}

Meht4409Meht4409

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....;

amjeremiadamjeremiad
Sarthak GuptaSarthak Gupta
Jose CifuentesJose Cifuentes

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;) {

user3742204user3742204

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 Mandal
6901 gold badge10 silver badges24 bronze badges
user3145373 ツ
5,1585 gold badges29 silver badges50 bronze badges
user3369245user3369245
Uche DimUche Dim
AmoghAmogh
BenjaminBenjamin
1,9171 gold badge9 silver badges16 bronze badges
VLS
1,9343 gold badges18 silver badges17 bronze badges
mister_geekmister_geek
chandanchandan

Simple 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.

Kazi ShahjahanKazi Shahjahan

Please go through my approach.It will provide you correct output:-

Rishabh KasliwalRishabh Kasliwal

this function will take a string as input and would reverse the string.

Abhishek DhimanAbhishek Dhiman
Kohei TAMURA
2,9663 gold badges12 silver badges32 bronze badges
Piyush GargPiyush Garg
Владимир СафоновВладимир Сафонов

Java Program To Reverse Individual Words In A Sentence

Ganesh BabuGanesh Babu
JilsonJilson

input: Hello i am ashish

output: ashish am i Hello

Java Program To Reverse The Words In A Sentence Pdf

Ashish PandeyAshish Pandey

Java Program To Reverse The Words In A Sentence In Place

Not the answer you're looking for? Browse other questions tagged javastringreverse or ask your own question.