How to reverse words in a sentence without using array or split or string tokenizer in Java?
h
SolarBoom (71)

how to reverse words in a sentence without using split orarray or string tokenizer.
I/p :- how are you
O/p :- you are how

You are viewing a single comment. View All
Edgod (58)

I used a for loop to compare each char from the end to the beginning of the string. When a space is found before the word, substring gets the word, including the space after it. Since there is no space before the first word of the sentence, the word gets added outside the loop.

This is what I figured out, although there could be a better way to do it.
(I'm not very familiar with Java)

import java.util.*;
class Main {
  public static void main(String[] args) {
    System.out.print("Input: ");
    Scanner input = new Scanner(System.in);
    String sentence;
    String reversed = "";
    int endIndex;
    
    sentence = input.nextLine();
    sentence += " "; //add a space to get the last word of sentence
    endIndex = sentence.length() - 1;
    //reverses every word except the first one
    for(int i = endIndex; i >= 0; i--){
      if(sentence.charAt(i) == ' '){
        reversed += sentence.substring(i + 1, endIndex + 1);
        endIndex = i;
      }
    }
    reversed += sentence.substring(0, endIndex); //add the first word
    System.out.println(reversed);
  }
}