翻译句子中每个单词中的字符 - 堆栈实现 [英] Reversing characters in each word in a sentence - Stack Implementation

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

问题描述

此代码位于 main 函数内:

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());
}

通过输入它无法正常工作例句我得到这个输出: 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 拆分函数,遍历单词,并反转他们的订单。

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();
}

方法已更改为:

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();

这篇关于翻译句子中每个单词中的字符 - 堆栈实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆