Reversing characters in each word in a sentence - Stack Implementation

前端 未结 6 1419
情深已故
情深已故 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:36

    Assuming you've already got your input in sentence and the Stack object is called stk, here's an idea:

    char[] tokens = sentence.toCharArray();
    for (char c : tokens) {
        if (c == ' ') {
            stk.empty();
            System.out.print(c);
        } else  {
            stk.add(c);
        }
    }
    

    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 like if (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.)

提交回复
热议问题