Reversing characters in each word in a sentence - Stack Implementation

前端 未结 6 1428
情深已故
情深已故 2020-12-22 06:02

This code is inside the main function:

Scanner input = new Scanner(System.in);

System.out.println(\"Type a sentence\");
String sentence = input         


        
6条回答
  •  醉话见心
    2020-12-22 06:12

    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.

    String[] words = sentence.split(" "); // splits on the space between words
    
    for (int i = 0; i < words.length; i++) {
        String word = words[i];
        System.out.print(reverseWord(word));
    
        if (i < words.length-1) {
            System.out.print(" "); // space after all words but the last
        }
    }
    

    Where the method reverseWord is defined as:

    public String reverseWord(String word) {
        for( int i = 0; i < word.length(); i++) {
            stk.push(word.charAt(i));
        }
        return stk.empty();
    }
    

    And where the empty method has been changed to:

    public String empty() {
        String stackWord = "";
        while (this.first != null)
            stackWord += this.pop();
        return stackWord;
    }
    

    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:

    1. Read each character from the input string and push that character to the stack
    2. When the input string is empty, pop each character from the stack and print it to screen.

    So:

    for( int i = 0; i < sentence.length(); i++) {
        stk.push(sentence.charAt(i));
    }
    stk.empty();
    

提交回复
热议问题