So my problem is about getting reversed String but only words which are longer or equals 5 characters.
So if we pass ("Hey fellow warriors") to the method we should get "Hey wollef sroirraw" in return. And my code gives me some weird results which are = "sroirraw fellow warriors ".
Here is my code, please give me some clue. The whitespace after last word shouldn't be returned but I don't know why it is.
public class PrimeChecker {
public String spinWords(String sentence) {
String[] tablica = sentence.split(" ");
for ( String x : tablica ) {
int y = 0;
if ( x.length() >= 5 ) {
StringBuilder p = new StringBuilder(x).reverse();
x = p.toString();
}
tablica[y] = x;
y++;
}
StringBuilder wynik = new StringBuilder();
for ( String z : tablica ) {
int y = 0;
tablica[y] = z;
wynik.append(tablica[y]);
if (tablica.length > 1 && y != tablica.length - 1 ) {
wynik.append(" ");
}
y++;
}
return wynik.toString();
}
}
Tester
public class PrimeCheckerTest {
public static void main(String[] args) {
PrimeChecker obiekt = new PrimeChecker();
System.out.println(obiekt.spinWords("Hey fellow warriors").toString());
}
}
First, I would prefer to split with \\s+ which matches one or more white-space characters. Second, I would use a lambda with Arrays.stream on the tokens I split. Then I would map each word, reversing every word with 5 or more characters. That can be done with a StringBuilder and reverse(). And since this method doesn't need any instance state we can make it static. Finally, join the words backs together with a Collector. Like,
public static String spinWords(String sentence) {
return Arrays.stream(sentence.split("\\s+"))
.map(s -> s.length() >= 5 ? new StringBuilder(s).reverse().toString() : s)
.collect(Collectors.joining(" "));
}
And to test it
public static void main(String[] args) {
System.out.println(spinWords("Hey fellow warriors"));
}
Which gives (as specified)
Hey wollef sroirraw
This code below will work. You have added y=0 inside the loop. That is unnecessary.
public class PrimeChecker {
public String spinWords(String sentence) {
String[] tablica = sentence.split(" ");
int y = 0;
for ( String x : tablica ) {
if ( x.length() >= 5 ) {
StringBuilder p = new StringBuilder(x).reverse();
x = p.toString();
}
tablica[y] = x;
y++;
}
StringBuilder wynik = new StringBuilder();
y=0;
for ( String z : tablica ) {
tablica[y] = z;
wynik.append(tablica[y]);
if (tablica.length > 1 && y != tablica.length - 1 ) {
wynik.append(" ");
}
y++;
}
return wynik.toString();
}
}
you need to define y out of for loop and before the second loop give it the value of zero , because you reset the value of y each loop .
You can do it in a simpler way:
public String spinWords(String sentence) {
String[] tablica = sentence.split(" ");
for (int i = 0; i < tablica.length; i++) {
if(tablica[i].length() >= 5) {
StringBuilder p = new StringBuilder(tablica[i]).reverse();
tablica[i] = p.toString();
}
}
StringBuilder builder = new StringBuilder();
for(String s : tablica) {
builder.append(s + " ");
}
String str = builder.toString();
return str;
}
Related
I am trying to cut a long string into lines of that string, the length of the lines is decided by the function. The function will not cut the words in the middle.
I have attempted many ways to do so using substrings and such but I am not that great at string manipulation. I have found a similar issue online, but it was in JavaScript and some of the code I could not fully translate to Java (maybe because i'm inexperienced with it...)
public static List<String> descriptionFormatter(String string, int amt)
{
String[] splitted = string.split(" ");
String part = "";
List<String> finalDesc = new ArrayList<String>();
for(int i = 0 ; i < splitted.length; i++)
{
part = part + " " + splitted[i];
if(part.length() >= amt)
{
finalDesc.add(part);
part = "";
}
}
return finalDesc;
}
e.g.
I have a string "hello world apple orange grapes juice spagehtti sauce milk"
and I want to cut it every 34 characters (considering all the requirements above)
so I call
descriptionFormatter(string, 34);
wanted result a string array/list:
hello world apple orange grapes juice
spagehtti sauce milk
actual result:
hello world apple orange grapes juice
I have gotten as far as almost getting it to work, but it sometimes it skips the remaining words at the end and puts spaces before the first word. How do I make it function as I intend it to?
You could try traversing the input string with two indexes say beginIndex and endIndex and take substrings from the input string as you go:
public static List<String> descriptionFormatter(String str, int amt) {
List<String> result = new ArrayList<>();
// trim the input string to avoid empty strings at the end
str = str.trim();
int beginIndex = 0;
int endIndex = amt;
final int length = str.length();
while(endIndex < length) {
// if we landed on something other than space
// increase the end index for the substring
// until we hit a space
while(endIndex < length && str.charAt(endIndex) != ' ') {
++endIndex;
}
result.add(str.substring(beginIndex, endIndex).trim());
beginIndex = endIndex;
endIndex += amt;
}
// Add the last string if any left
if(beginIndex < length) {
result.add(str.substring(beginIndex).trim());
}
return result;
}
public static void main(String[] args) {
String str = "hello world apple orange grapes juice spagehtti sauce milk";
descriptionFormatter(str, 34).forEach(System.out::println);
}
Output:
hello world apple orange grapes juice
spagehtti sauce milk
Try doing it like this
static List<String> split(String s, int size) {
return split(s.toCharArray(), size);
}
static List<String> split(char[] s, int size) {
List<String> strs = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length; ++i) {
if (i % size == 0) {
if(s[i] == ' ') {
strs.add(sb.toString());
sb = new StringBuilder();
}else {
StringBuilder newStringBuilder = new StringBuilder();
int length = sb.length();
while (length > 0 && sb.charAt(length - 1) != ' ') {
newStringBuilder.insert(0, sb.charAt(length - 1));
sb.deleteCharAt(length - 1);
--length;
}
if(sb.length() > 0) strs.add(sb.toString());
sb = newStringBuilder;
}
}
sb.append(s[i]);
}
if (sb.length() > 0) {
strs.add(sb.toString());
}
return strs;
}
public static List<String> descriptionFormatter(String string, int amt) {
List<String> stringPieces = new ArrayList<>();
StringBuilder strOfMaxLen = new StringBuilder();
StringBuilder strExceedsMaxLen = new StringBuilder();
String[] splitted = string.split(" ");
for (int i = 0 ; i < splitted.length; i++) {
String piece = splitted[i];
int pieceLen = piece.length();
if (strOfMaxLen.length()+pieceLen < amt) {
if (strOfMaxLen.length() != 0) {
strOfMaxLen.append(" ");
}
strOfMaxLen.append(piece);
} else {
if (strExceedsMaxLen.length() != 0) {
strExceedsMaxLen.append(" ");
}
strExceedsMaxLen.append(piece);
}
}
stringPieces.add(strOfMaxLen.toString());
stringPieces.add(strExceedsMaxLen.toString());
return stringPieces;
}
and yet another :)
private static List<String> descriptionFormatter(String string, int amt){
String[] splitted = string.split(" ");
List<String> ans = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (String s : splitted) {
if (sb.length() + s.length() > amt) {
ans.add(sb.toString()); // end the line add to list
sb.setLength(0); //clear the current string
} else {
if (sb.length()!=0)
sb.append(" "); // if it's the first don't add a space
sb.append(s); // add the word
}
}
ans.add(sb.toString());// add the last line
return ans;
}
I have a string
"Red apple, blue banana, orange".
How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :
Pattern pattern = Pattern.compile(", ");
List<Fruit> f = pattern.splitAsStream(fruitString)
.map(Fruit::valueOf)
.collect(Collectors.toList());
Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.
Use map(...) method to perform transformations on the original String. Instead of calling Fruit::valueOf through a method reference, split each string on space inside map(...), and construct a combined string when you get exactly two parts:
List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
.map(s -> {
String[] parts = s.split(" ");
String tmp = parts.length == 2
? parts[0]+"_"+parts[1]
: s;
return Fruit.valueOf(tmp.toUpperCase());
}).collect(Collectors.toList());
Demo.
If you need to perform any additional transformations of the result, you can do them in the same lambda code block prior to the return statement.
Here is another sample:
f = pattern.splitAsStream(fruitString)
.map(s -> Arrays.stream(s.split(" ")).map(String::toUpperCase).collect(Collectors.joining("_")))
.map(Fruit::valueOf).collect(Collectors.toList());
Or by StreamEx:
StreamEx.split(fruitString, ", ")
.map(s -> StreamEx.split(s, " ").map(String::toUpperCase).joining("_"))
.map(Fruit::valueOf).toList();
Your Enum
static enum Fruit {
RED_APPLE, BLUE_BANANA, ORANGE
}
Main code:
public static void main(String[] ar) throws Exception {
Pattern pattern = Pattern.compile(", ");
List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
.map(YourClass::mapToFruit)
.collect(Collectors.toList());
System.out.println(f);
}
Helper method to offload dirty mapping part
private static Fruit mapToFruit(String input) {
String[] words = input.split("\\s");
StringBuilder sb = new StringBuilder();
if (words.length > 1) {
for (int i = 0; i < words.length - 1; i++) {
sb.append(words[i].toUpperCase());
sb.append("_");
}
sb.append(words[words.length - 1].toUpperCase());
} else {
sb.append(words[0].toUpperCase());
}
return Fruit.valueOf(sb.toString());
}
To split the string you can do:
string[] output = fruitString.split(",");
You would then have to go through the string letter by letter to find spaces and replace them with strings:`
for(int i = 0; i < output.length; i++){
for(int j = 0; j < output[i].length(); j++){
char c = output[i].charAt(j);
//check for space and replace with _
}
}
then using the .toUpperCase() to conver the first char to a upper letter
Hope this helps you.
Please find the below Code, I have followed the below Steps :
1) Split the String by , first.
2) Again split the result of 1) String by " ".
3) Then if the word counts are more than 1 then only proceed to append the underscore.
Demo:
http://rextester.com/NNDF87070
import java.util.*;
import java.lang.*;
class Rextester
{
public static int WordCount(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
public static void main(String args[])
{
String cord = "Red apple , blue banana, orange";
String[] parts = cord.split(",");
String[] result1 = new String[parts.length];
for(int i=0; i<parts.length;i++) {
String[] part2 = parts[i].split(" ");
if(parts[i].length() > 1 && WordCount(parts[i]) > 1)
{
String result = "_";
String uscore = "_";
for(int z =0; z < part2.length; z++)
{
if(part2.length > 1 ) {
if (z + 1 < part2.length) {
result = part2[z] + uscore + part2[z + 1];
}
}
}
result1[i] = result.toUpperCase();
}
else
{
result1[i] = parts[i];
}
}
for(int j =0 ; j <parts.length; j++)
{
System.out.println(result1[j]);
}
}
}
References for the WordCount Method: Count words in a string method?
String yourString = "Red apple, blue banana, orange";
stringArray = yourString.split(", ");
List<string> result;
//stringArray will contain 3 strings
//Red apple
//blue banana
//orange
for(string s : stringArray) {
//Replace all spaces with underscores
result.add(s.replace(" ", "_").toUpperCase());
}
I have this sequence "ggtacctcctacgggaggcagcagtgaggaattttccgcaatgggcgaaagcctgacgga" and I want to break it into 3char length units like ggt acc tcc ..etc?
Try something like:
String str[] = s.split("(?<=\\G...)");
Output
[ggt, acc, tcc, tac, ggg, agg, cag, cag, tga, gga, att, ttc, cgc, aat, ggg, cga, aag, cct, gac, gga]
You could try something like the following, where you could convert the String to a char[] and loop through them in units of 3 in order to get that String:
String str = "ggtacctcctacgggaggcagcagtgaggaattttccgcaatgggcgaaagcctgacgga";
char[] array = str.toCharArray();
List<String> result = new ArrayList<String>();
for(int i = 0; i<array.length; i+=3)
{
StringBuilder s = new StringBuilder();
for(int j = i ; j<array.length && j < i+3; j++)
{
s.append(array[j]);
}
result.add(s.toString());
}
The List results now contains strings of length three, and it does not break if the size is not a multiple of three.
Here is another solution that uses the substring method (without StringTokenizer):
public static void main(String[] args) {
String s = "ggtacctcctacgggaggcagcagtgaggaattttccgcaatgggcgaaagcctgacgga";
char[][] c = new char[s.length()/3][3];
for ( int i = 0 ; i < s.length() ; i+=3 ) {
String substring = s.substring(i, i+3);
c[i/3] = substring.toCharArray();
}
// test
for ( int i = 0 ; i < c.length ; i++ ) {
for ( int j = 0 ; j < c[0].length ; j++ ) {
System.out.print(c[i][j]);
}
System.out.println();
}
}
Do not use a Stringtokenizer. The regular expression to split is really inefficient - DNA/RNA-Strings are really long.
In Java 8 one could do following solution:
public static void main(String[] args) {
String str = "ggtacctcctacgggaggcagcagtgaggaattttccgcaatgggcgaaagcctgacgga";
List<String> collect = str.chars()
.mapToObj(accumulator(3))
.filter(s -> s != null)
.collect(Collectors.toList());
System.out.println(collect);
}
private static IntFunction<String> accumulator(final int size) {
return new CharAccumulator(size);
}
private static final class CharAccumulator implements IntFunction<String> {
private StringBuilder builder ;
private int size;
private CharAccumulator(int size) {
this.builder = new StringBuilder();
this.size = size;
}
#Override
public String apply(int value) {
builder.append((char) value);
if (builder.length() == size) {
String result = builder.toString();
builder.setLength(0);
return result;
} else {
return null;
}
}
}
It is not as easy to understand and maybe not as performant but it works also with lazy char streams (saves memory).
I'm suppose to replace a "L" in a string every time it is found in the string HELLO WORLD, with "x". and the x is to increased every occurrence of L.
input: "HELLO WORLD"
output: "HExxxO WORxxxD"
use only String methods: .length; .indexOf; .substring
and .concat (or +).
EDIT
Here's my try:
public static String replace(String input,String pattern) {
String result = " ";
int stringLength;
int patternIndex;
while (input !=null) {
patternIndex = input.indexOf(pattern);
stringLength = input.length();
}
return result;
}
i only find the index of the pattern and the length of the string having problem with replacing the character.
First: sane solution:
StringBuilder sb = new StringBuilder();
StringBuilder r = new StringBuilder();
for( char c : "HELLO LAZY LIMBO WORLD" .toCharArray() ) {
if( c == 'L' ) {
sb.append(r.append('x'));
} else {
sb.append( c );
}
}
return sb.toString() );
Then modified to meed the criteria of only using valid methods .length; .indexOf; .substring and .concat (or +) ( removing toCharArray(); and StringBuilder )
public static String replace( String input ){
String replacement = "";
int iot = -1;
while( ( iot = input.indexOf('L')) > -1 ) {
input = input.substring(0,iot) +
( replacement+='x' ) +
input.substring(iot+1);
}
return input;
}
That one look like a for loop. Let's change it!
With only two statements ( declr and a for loop ):
public static String replace( String in ){
String x = "";
for( int i = 0; ( i = in.indexOf('L',i)) > -1 ;
in = in.substring(0,i++) + ( x=x+'x' ) + in.substring(i) );
return in;
}
Yields:
HExxxO xxxAZY xxxxIMBO WOxxxxxR
Now, that's! a for loop. I almost make Java look like perl.
static String xform(String helloWorld) {
if (helloWorld.intern() != "HELLO WORLD")
throw new IllegalArgumentException("bad World");
return "HExxxO WORxxxD";
}
and here is a very special version for the ones w/o sense of humor: the special edition - loplez&funless
public class TheLoop {
public static void main(String[] args) throws Throwable{
System.out.println(xForm2("Hello World -L".toUpperCase(),0));
}
static String xForm2(String s,int k){
return k<-1?"x"+xForm2(s,k+1):(k==-1?"":("L".equals(s.substring(0,1))?xForm2(s,-(k+1)-1) :s.substring(0,1))+(s.length()==1?"":xForm2(s.substring(1), "L".equals(s.substring(0,1))?k+1:k)));
}
}
200 bounty if anyone manages to write the function in a single line (single semicolon) and uglier than this
String x_ify(String input) {
String output = "";
int start = 0;
int count = 0;
int nextL;
while ((nextL = input.indexOf('L', start)) >= 0) {
if (nextL > start) {
output = output + input.substring(start, nextL);
}
++count;
for (int i = 0; i < count; ++i) {
output = output + "x";
}
start = nextL + 1;
}
if (start < input.length()) {
output += input.substring(start);
}
return output;
}
char charToReplace = 'l';
String str = " Hello World";
char newChar = 'x';
String newString = "x";
StringBuilder result = new StringBuilder();
for (int index = 0; index < str.length(); index++) {
if (str.charAt(index) == charToReplace) {
result.append(newString);
newString += newChar;
} else {
result.append(str.charAt(index));
}
}
System.out.println(result);
Note: it can be optimized
A bodyless one-liner for statement, specially for bestsss:
public static String replace(String s) {
for (String x=""; s.indexOf('L') > -1 ; s = s.substring(0,s.indexOf('L')) + ( x=x+'x' ) + s.substring(s.indexOf('L')+1) );
return s;
}
Although not using the standard functions you mentioned but this is an alternate way:
public static void first()
{
String input = "HELLO WORLD";
String X = "";
int numofL = input.length() - input.replaceAll("L+", "").length();
for(int i=0;i<numofL;i++)
X += "x";
String output = input.replaceAll("L+", X);
System.out.println(output);
}
public static void main(String[] args) {
String input = "HELLO WORLD";
String output = "";
String repl = "x";
int idx, start = 0;
while ((idx = input.indexOf('L', start)) > 0) {
output += input.substring(start, idx);
output += repl;
start = idx + 1;
repl += "x";
}
if (start < input.length()) {
output += input.substring(start);
}
System.out.println(output);
}
public class Main {
public static void main(String[] args) {
System.out.println(replace("hello world", "x"));
}
public static String replace(String in, String xs) {
return in.indexOf("l") != -1 ? replace(in.substring(0, in.indexOf("l")) + xs + in.substring(in.indexOf("l") + 1), xs + "x") : in;
}
}
public class ReplaceChar {
public static void replaceChar(String s, StringBuilder sb, int depth){
int i = s.indexOf('L');
if(i==-1){
return;
}
else
sb.append(s.substring(0,i));
for(int j=depth;j>0;j--){
sb.append('x');
}
replaceChar(s.substring(i+1),sb,++depth);
}
public static void main(String[] args){
StringBuilder sb = new StringBuilder();
System.out.println("main "+sb);
replaceChar("HELLO WORLD",sb,1);
}
}
Can anyone tell me how to write a Java program to reverse a given sentence?
For example, if the input is:
"This is an interview question"
The output must be:
"question interview an is this"
You split the string by the space then iterate over it backwards to assemble the reversed sentence.
String[] words = "This is interview question".split(" ");
String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
rev += words[i] + " ";
}
// rev = "question interview is This "
// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
revb.append(words[i]);
revb.append(" ");
}
// revb.toString() = "question interview is This "
String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = StringUtils.join(reversedWords, " ");
(using ArrayUtils and StringUtils from commons-lang, but these are easy methods to write - just a few loops)
Just being different: a recursive solution. Doesn't add any extra spaces.
public static String reverse(String s) {
int k = s.indexOf(" ");
return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
}
System.out.println("[" + reverse("This is interview question") + "]");
// prints "[question interview is This]"
I will also improve on the split solution by using \b instead (it's so obvious!).
String[] parts = "Word boundary is better than space".split("\\b");
StringBuilder sb = new StringBuilder();
for (int i = parts.length; i --> 0 ;) {
sb.append(parts[i]);
}
System.out.println("[" + sb.toString() + "]");
// prints "[space than better is boundary Word]"
Bozho already gave a great Java-specific answer, but in the event you ever need to solve this problem without Java API methods:
To reverse, you can simply pop individual words onto a stack and pop them all back off when there are no words left.
(Just to be extra clear, Java does provide a Stack class, so it is possible to use this method in Java as well).
Just split it on a space character into a string array, then loop over the array in reverse order and construct the output string.
String input = "This is interview question";
String output = "";
String[] array = input.split(" ");
for(int i = array.length-1; i >= 0; i--)
{
output += array[i];
if (i != 0) { output += " "; }
}
a every boring bit of java:
List<String> l = new ArrayList<String>(Arrays.asList("this is an interview question".split("\\s")));
Collections.reverse(l);
StringBuffer b = new StringBuffer();
for( String s : l ){
b.append(s).append(' ');
}
b.toString().trim();
in groovy it's a little bit more readable:
"this is an interview question"
.split("\\s")
.reverse()
.join(' ')
I also give it a try: Here's a version using a stack and a scanner:
String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();
while(sc.hasNext()) {
stack.push(sc.next());
}
StringBuilder output = new StringBuilder();
for(;;) { // forever
output.append(stack.pop());
if(stack.isEmpty()) {
break; // end loop
} else {
output.append(" ");
}
}
public class ReverseString {
public void reverse(String[] source) {
String dest = "";
for (int n = source.length - 1; n >= 0; n--) {
dest += source[n] + " ";
}
System.out.println(dest);
}
public static void main(String args[]) {
ReverseString rs = new ReverseString();
String[] str = "What is going on".split(" ");
rs.reverse(str);
}
}
nicer approach probably.. had seen the logic somewhere..here is my code which might do the job.
public class revWords {
public static void main(String[] args) {
revWords obj = new revWords();
String print = obj.reverseWords("I am God");
System.out.println(print);
}
public String reverseWords(String words)
{
if(words == null || words.isEmpty() || !words.contains(" "))
return words;
String reversed = "";
for( String word : words.split(" "))
reversed = word + " " + reversed;
return reversed;
}
}
I don't think you should use any library..
1) Reverse whole string
2) Reverse each word.
public static void revWord(char[] a) {
// reverse whole
revWord(a, 0, a.length);
int st = -1;
int end = -1;
for (int i = 0; i < a.length; i++) {
if (st == -1 && a[i] != ' ') {
st = i;
}
if (end == -1 && a[i] == ' ' ) {
end = i;
}
if(i == a.length-1){
end=i+1;
}
if (st != -1 && end != -1) {
revWord(a, st, end );
st = -1;
end = -1;
}
}
}
public static void revWord(char[] a, int s, int l) {
int mid = (l - s) / 2;
l--;
for (int i = 0; i < mid; i++, l--) {
char t = a[s+i];
a[s+i] = a[l];
a[l] = t;
}
}
`
No one has mentioned a vanilla Java 8 based solution yet, which is the same as Bozho's, but without any third-party libraries. So here it is:
String input = "This is interview question";
List<String> list = Arrays.asList(input.split(" "));
Collections.reverse(list);
System.out.println(list.stream().collect(Collectors.joining(" ")));
please try below solution, this is working for me.
public class reverseline {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="This is interview question";
String words[]=str.split(" ");
for(int i=words.length-1;i>=0;i--){
System.out.print(words[i]+" ");
}
}
}
Before StringTokenizer was declared legacy, many used StringTokenizer for this. Thought I would just leave it here.
String sentence = "This is interview question";
String reversed = "";
StringTokenizer tokens = new StringTokenizer(sentence);
while (tokens.hasMoreTokens()) { // Loop through each token
reversed = tokens.nextToken() + ' ' + reversed; //add to start
}
System.out.println(reversed.trim());
Shortest Answer
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
List<String> reverseWord = Arrays.asList(words);
Collections.reverse(reverseWord);
Iterator itr = reverseWord.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}
OR
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
for (int i = words.length-1 ; i >= 0; i--) {
System.out.print(words[i] +" ");
}
}
}