This code is inside the main
function:
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence");
String sentence = input.next();
Stack<Character> stk = new Stack<Character>();
int i = 0;
while (i < sentence.length())
{
while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
{
stk.push(sentence.charAt(i));
i++;
}
stk.empty();
i++;
}
And this is the empty()
function:
public void empty()
{
while (this.first != null)
System.out.print(this.pop());
}
It doesn't work properly, as by typing example sentence
I am getting this output: lpmaxe
. The first letter is missing and the loop stops instead of counting past the space to the next part of the sentence.
I am trying to achieve this:
This is a sentence
---> sihT si a ecnetnes
}
This can pass in leetcode
public class ReverseofeachWordinaSentance {
}
Per modifications to the original post, where the OP is now indicating that his goal is to reverse the letter order of the words within a sentence, but to leave the words in their initial positions.
The simplest way to do this, I think, is to make use of the String
split
function, iterate through the words, and reverse their orders.Where the method
reverseWord
is defined as:And where the
empty
method has been changed to:Original response
The original question indicated that the OP wanted to completely reverse the sentence.
You've got a double-looping construct where you don't really need it.
Consider this logic:
So:
I assume that what you want your code to do is to reverse each word in turn, not the entire string. So, given the input
example sentence
you want it to outputelpmaxe ecnetnes
notecnetnes elpmaxe
.The reason that you see
lpmaxe
instead ofelpmaxe
is because your innerwhile
-loop doesn't process the last character of the string since you havei < sentence.length() - 1
instead ofi < sentence.length()
. The reason that you only see a single word is because yoursentence
variable consists only of the first token of the input. This is what the methodScanner.next()
does; it reads the next (by default) space-delimited token.If you want to input a whole sentence, wrap up
System.in
as follows:and call
reader.readLine()
.Hope this helps.
Assuming you've already got your input in
sentence
and the Stack object is calledstk
, here's an idea:Thus, it will scan through one character at a time. If we hit a space character, we'll assume we've hit the end of a word, spit out that word in reverse, print that space character, then continue. Otherwise, we'll add the character to the stack and continue building the current word. (If you want to also allow punctuation like periods, commas, and the like, change
if (c == ' ') {
to something likeif (c == ' ' || c == '.' || c == ',') {
and so on.)As for why you're only getting one word, darrenp already pointed it out. (Personally, I'd use a Scanner instead of a BufferedReader unless speed is an issue, but that's just my opinion.)
}