Ask coding questions

← Back to all posts
1
How to reverse words in a sentence without using array or split or string tokenizer in Java?
SolarBoom (44)

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

Answered by Edgod (58) [earned 5 cycles]
View Answer
Commentshotnewtop
1
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);
  }
}
1
SolarBoom (44)

@Edgod Thanks for the help

3
vedprad1 (470)

Why wouldn't you want to use split()? It is way more efficient.

1
SolarBoom (44)

@vedprad1 Split() makes things easier. But our efficiency comes when we are not dependent on the functions which are not the most important function of the stings.

1
Edgod (58)

@SolarBoom That doesn't make sense, unless I'm misunderstanding you. The split() method exists so that programmers wouldn't have to reinvent the wheel, which makes Java more efficient. It's just a function. The answer I gave you above is me literally redoing split() in a different way. I thought you asked the question because you were curious.

1
SolarBoom (44)

@Edgod That's true too. I was actually curious