如何在Java中向后打印多个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19016446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:24:42  来源:igfitidea点击:

How to print several strings backwards in Java

javastringfor-loopreverse

提问by S12

I am trying to take a file full of strings, read it, then print out a few things:

我正在尝试获取一个充满字符串的文件,读取它,然后打印出一些内容:

  • The string
  • The string backwards AND uppercase
  • The string length
  • 字符串
  • 字符串向后和大写
  • 字符串长度

There are a few more things, however I haven't even gotten to that point and do not want to ask anyone to write the code entirely for me. After messing around with it for a while, I have it almost completed (I believe, save for a few areas).

还有一些事情,但是我什至还没有达到那个点,并且不想要求任何人完全为我编写代码。搞了一段时间之后,我差不多完成了(我相信,除了一些区域)。

The piece that is tripping me up is the backwards word. We are required to put our output neatly into columns using prinf, but I cannot do this if I read each char at a time. So I tried setting a String backwardsWord = "";and adding each character.

让我绊倒的部分是倒退词。我们需要使用 prinf 将我们的输出整齐地放入列中,但是如果我一次读取每个字符,我就无法做到这一点。所以我尝试设置 aString backwardsWord = "";并添加每个字符。

This is the piece that is tripping me up:

这是让我绊倒的部分:

for(int i = upperCaseWord.length() - 1; i >= 0; i--)
{
    backwardsWord += (upperCaseWord.charAt(i) + "");
}   

My issue is that when I print it, the first word works properly. However, each word after that is added to the previous word.

我的问题是,当我打印它时,第一个单词可以正常工作。但是,之后的每个单词都会添加到前一个单词上。

For example: if I am printing cat, dog, and rat backwards, it shows

例如:如果我向后打印猫、狗和老鼠,它显示

TAC

TACGOD

TACGODTAR

TAC

TACGOD

塔哥达

I obviously want it to read

我显然希望它阅读

TAC

GOD

TAR

TAC

上帝

柏油

Any help would be appreciated.

任何帮助,将不胜感激。

回答by n00begon

It looks like your variable backwardsWordis always appending a character without being reset between words. The simplest fix is to clear the backwardsWordjust before your loop by setting it to empty string.

看起来您的变量backwardsWord总是附加一个字符而不会在单词之间重置。最简单的解决方法是backwardsWord通过将其设置为空字符串来清除循环之前的内容。

backwardsWord = ""; //Clear any existing characters from backwardsWord

for(int i = upperCaseWord.length() - 1; i >= 0; i--)
{
    backwardsWord += (upperCaseWord.charAt(i) + "");
}


If you are building up a String one character at a time you will be using a lot of memory because Java Strings are immutable.


如果您一次构建一个字符串,您将使用大量内存,因为Java 字符串是不可变的

To do this more efficiently use a StringBuilderinstead. This is made for building up characters like what you are doing. Once you have finished you can use the toStringmethod to get the String out.

要更有效地执行此操作,请改用StringBuilder。这是为了建立像你在做什么的角色。完成后,您可以使用该toString方法将字符串取出。

StringBuilder builder = new StringBuilder(); //Creates the String builder for storing the characters
for(int i = upperCaseWord.length() - 1; i >= 0; i--)
{
    builder.append(upperCaseWord.charAt(i)); //Append the characters one at a time 
}
backwardsWord = builder.toString(); //Store the finished string in your existing variable

This has the added benefit of resetting the backwardsWord each time.

这有一个额外的好处,就是每次都重置向后词。


Finally, since your goal is to get the String in reverse we can actually do it without a loop at all as shown in this answer


最后,由于您的目标是反向获取字符串,因此我们实际上可以在没有循环的情况下做到这一点,如本答案所示

backwardsWord = new StringBuilder(upperCaseWord).reverse().toString()

This creates a new StringBuilderwith the characters from upperCaseWord, reverses the characters then stores the final string in backwardsWord

这将StringBuilder使用 from 的字符创建一个新的upperCaseWord,反转字符然后将最终字符串存储在backwardsWord

回答by dganesh2002

This should do the job ->

这应该可以完成工作->

class ReverseWordsInString{
public static String reverse(String s1){
        int l = s1.length();
        if (l>1)
                return(s1.substring(l-1) + reverse(s1.substring(0,l-1)));
        else
                return(s1.substring(0));
  }
public static void main(String[] args){
        String st = "Cat Dog Rat";
        String r = "";
        for (String word : st.split(" "))
                r += " "+ reverse(word.toUpperCase());
        System.out.println("Reversed words in the given string: "+r.trim());
  }
}

回答by miss.serena

Where are you declaring the String backwardsWord?

你在哪里声明字符串向后?

If you don't clear it between words then the memory space allocated to that string will still contain the previously added characters.

如果您不在单词之间清除它,则分配给该字符串的内存空间仍将包含先前添加的字符。

Make sure you are tossing in a backwardsWord = ""; in between words to reset it's value and that should fix your problem.

确保你在向后折腾Word = ""; 在单词之间重置它的值,这应该可以解决您的问题。

Without seeing more of your code I can't tell you exactly where to put it.

没有看到你的更多代码,我无法告诉你把它放在哪里。