简体   繁体   English

在 Java 中反转字符串(非字符)中的单词

[英]Reversing words in a string (NOT characters) in Java

I am very new to coding, and I am trying to solve the following question:我对编码很陌生,我正在尝试解决以下问题:
Use a stack to reverse the words of a sentence.使用堆栈来反转句子的单词。 Keep reading words until you have a word that ends in a period, adding them onto a stack.继续阅读单词,直到有一个以句号结尾的单词,然后将它们添加到堆栈中。 When you have a word with a period, pop the words off and print them.当你有一个带句号的单词时,把这些单词弹出并打印出来。 Stop when there are no more words in the input.当输入中没有更多单词时停止。 For example, you should turn the input:例如,您应该打开输入:
Mary had a little lamb.玛丽有只小羊羔。 Its fleece was white as snow.它的羊毛洁白如雪。
into:进入:
Lamb little a had mary.小羊羔点了玛丽。 Snow as white was fleece its.雪白如羊毛。
Pay attention to capitalization and the placement of the period.注意大写和句号的位置。

I am struggling to find how to reverse the words - I have found a lot of examples of reversing characters, but I can't get anything to work to reverse full words.我正在努力寻找如何反转单词 - 我发现了很多反转字符的例子,但我无法得到任何工作来反转完整的单词。 Here is what I have so far.这是我到目前为止所拥有的。 I don't really understand the String[] words = sentence.split(" ");我不太明白 String[] words = sentence.split(" "); line, but I found that in a lot of solutions... Is that creating an array of words that I can then push onto the stack?行,但我在很多解决方案中都发现了这一点......是否创建了一组单词,然后我可以将其压入堆栈?

import java.util.Scanner;
import java.util.Stack;

public class Task03 {
public static void main(String[] args) {
    String sentence;
    System.out.println("Enter a sentence: ");
    Scanner input = new Scanner(System.in);
    sentence = input.next();

    printStack(sentence);        
}

private static void printStack(String sentence) {
    Stack<String> stack = new Stack<>();
    String[] sentenceArray = sentence.split(" ");
    String reversed = "";

    for (String words: sentenceArray) {
        stack.push(words);
    }
    while (!stack.isEmpty()){
        reversed += stack.pop();
    }
    System.out.println("Reverse is: " + reversed);
}
}


The output for this just returns the first word from the sentence, so I'm doing something wrong in the printStack method.这个输出只返回句子中的第一个单词,所以我在 printStack 方法中做错了。 I hope I have added enough to show you that I am really trying.我希望我已经添加了足够的内容来告诉你我真的很努力。

I have hard coded the string value.我对字符串值进行了硬编码。 you can take input from user too您也可以从用户那里获取输入

class StringRev{
    public static void main(String args[]){
    String str = "He is the one";
    String temp = "";
    String finalString = "";
        for(int i =str.length()-1;i>=0;i--){
            temp +=i!=0?str.charAt(i):str.charAt(i)+" ";
            if(str.charAt(i) == ' '||i==0){
                for(int j=temp.length()-1;j>=0;j--){
                    finalString += temp.charAt(j);
                }
                temp = "";
            }
        }
            System.out.println(finalString);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM