Java 在句子堆栈实现中反转每个单词中的字符

Java 在句子堆栈实现中反转每个单词中的字符,java,stack,reverse,Java,Stack,Reverse,此代码在主功能中: 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.c

此代码在
主功能中:

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++;
}
public void empty()
{
    while (this.first != null)
        System.out.print(this.pop());
}
它不能正常工作,因为通过键入
示例句子
我得到以下输出:
lpmaxe
。第一个字母丢失,循环停止,而不是从空格数到句子的下一部分

我正努力做到这一点:


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

根据对原始帖子的修改,OP现在表示他的目标是颠倒句子中单词的字母顺序,但保留单词的初始位置

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

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
    }
}
其中,
方法已更改为:

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

最初的问题表明OP想要完全颠倒句子

你有一个双循环结构,你并不需要它

考虑一下这个逻辑:

  • 从输入字符串中读取每个字符,并将该字符推送到堆栈中
  • 当输入字符串为空时,从堆栈中弹出每个字符并将其打印到屏幕上
  • 因此:

    for(int i=0;i<句子长度();i++){
    stk.push(句子特征(i));
    }
    stk.empty();
    
    根据对原始帖子的修改,OP现在表示他的目标是颠倒句子中单词的字母顺序,但保留单词的初始位置

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

    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
        }
    }
    
    其中,
    方法已更改为:

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

    最初的问题表明OP想要完全颠倒句子

    你有一个双循环结构,你并不需要它

    考虑一下这个逻辑:

  • 从输入字符串中读取每个字符,并将该字符推送到堆栈中
  • 当输入字符串为空时,从堆栈中弹出每个字符并将其打印到屏幕上
  • 因此:

    for(int i=0;i<句子长度();i++){
    stk.push(句子特征(i));
    }
    stk.empty();
    
    我假设您希望代码做的是依次反转每个单词,而不是整个字符串。因此,给定输入的
    示例语句
    您希望它输出
    elpmaxe-ecnetnes
    而不是
    ecnetnes-elpmaxe

    之所以看到的是
    lpmaxe
    而不是
    elpmaxe
    ,是因为内部
    while
    -loop没有处理字符串的最后一个字符,因为您使用的是
    i
    而不是
    i
    。之所以只看到一个单词,是因为
    语句
    变量只包含输入的第一个标记。这就是方法
    Scanner.next()
    的作用;它读取下一个(默认情况下)以空格分隔的令牌

    如果您想输入一个完整的句子,请在
    中对系统进行总结,如下所示:

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    
    并调用
    reader.readLine()


    希望这有帮助。

    我假设您希望代码做的是依次反转每个单词,而不是整个字符串。因此,给定输入的
    示例语句
    您希望它输出
    elpmaxe-ecnetnes
    而不是
    ecnetnes-elpmaxe

    之所以看到的是
    lpmaxe
    而不是
    elpmaxe
    ,是因为内部
    while
    -loop没有处理字符串的最后一个字符,因为您使用的是
    i
    而不是
    i
    。之所以只看到一个单词,是因为
    语句
    变量只包含输入的第一个标记。这就是方法
    Scanner.next()
    的作用;它读取下一个(默认情况下)以空格分隔的令牌

    如果您想输入一个完整的句子,请在
    中对系统进行总结,如下所示:

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    
    并调用
    reader.readLine()


    希望这能有所帮助。

    假设您已经在
    语句中获得了输入,并且堆栈对象名为
    stk
    ,下面是一个想法:

    char[] tokens = sentence.toCharArray();
    for (char c : tokens) {
        if (c == ' ') {
            stk.empty();
            System.out.print(c);
        } else  {
            stk.add(c);
        }
    }
    
    因此,它将一次扫描一个字符。如果我们碰到一个空格字符,我们会假设我们碰到了一个单词的结尾,把这个单词倒过来吐出来,打印那个空格字符,然后继续。否则,我们将把字符添加到堆栈中并继续构建当前单词。(如果您还希望允许句点、逗号等标点符号,请将
    If(c=''){
    更改为
    If(c=''| | c='.| c='.| c='.'){
    等。)


    至于为什么你只得到一个单词,darrenp已经指出了。(就我个人而言,我会使用扫描仪而不是缓冲读取器,除非速度是个问题,但这只是我的观点。)

    假设你已经在
    句子中得到了输入,堆栈对象被称为
    stk
    ,下面是一个想法:

    char[] tokens = sentence.toCharArray();
    for (char c : tokens) {
        if (c == ' ') {
            stk.empty();
            System.out.print(c);
        } else  {
            stk.add(c);
        }
    }
    
    因此,它将一次扫描一个字符。如果我们击中一个空格字符,我们将假定我们击中了一个单词的结尾,将该单词反向吐出,打印该空格字符,然后继续。否则,我们将把该字符添加到堆栈中并继续构建当前单词。(如果您还希望允许句点、逗号等标点符号,请将
    If(c=''){
    更改为
    If(c=''| | c='.| c='.| c='.'){
    等。)

    至于为什么你只得到一个单词,darrenp已经指出了这一点。(就我个人而言,除非速度是个问题,否则我会使用扫描仪而不是BufferedReader,但这只是我的观点。)

    }


    }

    公共类反向FeachWordInAsentance{

    /**
     * @param args
     */
    public static void main(String[] args) {
        String source = "Welcome to the word reversing program";
    
        for (String str : source.split(" ")) {
            System.out.print(new StringBuilder(str).reverse().toString());
            System.out.print(" ");
        }
    System.out.println("");
    
        System.out.println("------------------------------------ ");
        String original = "Welcome to the word reversing program";
        wordReverse(original);
        System.out.println("Orginal Sentence :::: "+original);
        System.out.println("Reverse Sentence :::: "+wordReverse(original));
    }
    
    public static String wordReverse(String original){
    
        StringTokenizer string = new StringTokenizer(original);
    
        Stack<Character> charStack = new Stack<Character>();
    
        while (string.hasMoreTokens()){
    
        String temp = string.nextToken();
    
        for (int i = 0; i < temp.length(); i ++){
    
        charStack.push(temp.charAt(i));
    }
        charStack.push(' ');
    }
    
        StringBuilder result = new StringBuilder();
        while(!charStack.empty()){
        result.append(charStack.pop());
    }
    
        return result.toString();   
    }