反转句子中每个单词中的字符 - Thinbug

Reversing characters in each word in a sentence - Stack Implementation(反转句子中每个单词中的字符 - Thinbug)

本文介绍了反转句子中每个单词中的字符 - Thinbug的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码在 main 函数中:

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++;
}

这是 empty() 函数:

public void empty()
{
    while (this.first != null)
        System.out.print(this.pop());
}

它不能正常工作,因为通过输入 example sentence 我得到这个输出:lpmaxe.第一个字母丢失,循环停止,而不是从空格算到句子的下一部分.

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:

这是一个句子 ---> sihT si a ecnetnes

推荐答案

根据对原帖的修改,OP现在表示他的目标是反转句子中单词的字母顺序,但要留下单词在它们的初始位置.

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.

我认为最简单的方法是使用 String split 函数,遍历单词,并颠倒它们的顺序.

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
    }
}

其中reverseWord方法定义为:

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

empty 方法已更改为:

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

原始回复

原来的问题表明OP想要完全颠倒句子.

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.

考虑这个逻辑:

  1. 从输入字符串中读取每个字符并将该字符压入堆栈
  2. 当输入字符串为空时,从堆栈中弹出每个字符并打印到屏幕上.

所以:

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

这篇关于反转句子中每个单词中的字符 - Thinbug的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:反转句子中每个单词中的字符 - Thinbug

基础教程推荐