java Java反向字符串方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49126461/
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-11-03 10:16:50  来源:igfitidea点击:

Java reverse string method

javastring

提问by Dummy

I'm tying to learn Java. I need to make a method called reverse that gets a string and return a string (but in reverse order). Here is what i tried. Can you fix the code and explain what I'm doing wrong? Please also give me some advice about a good start in Java. Thank you!

我正在学习 Java。我需要创建一个名为 reverse 的方法来获取一个字符串并返回一个字符串(但顺序相反)。这是我尝试过的。你能修复代码并解释我做错了什么吗?还请给我一些有关 Java 良好开端的建议。谢谢!

public class Test{
    public static String reverse(String a){  
        int j = a.length();
        char[] newWord = new char[j];
        for(int i=0;i<a.length();i++)
        {
            newWord[j] = a.charAt(i);
            j--;
        }
        return new String(newWord);
    }

    public static void main(String a[]){

        String word = "abcdefgh";
        System.out.println(reverse(word));
    }
}

回答by Axel Ros

You can use this to reverse the string, you don't need to use your own method

你可以用这个来反转字符串,你不需要用你自己的方法

new StringBuilder(word).reverse().toString()

If you want to use your solution you must change int j = a.length() to int j = a.length() -1;

如果您想使用您的解决方案,您必须将 int j = a.length() 更改为 int j = a.length() -1;

回答by Can't Tell

The fixed code is

固定代码是

public class Test {
    public static String reverse(String a) {
        int j = a.length();
        char[] newWord = new char[j];
        for (int i = 0; i < a.length(); i++) {
            newWord[--j] = a.charAt(i);
        }
        return new String(newWord);
    }

    public static void main(String a[]) {

        String word = "abcdefgh";
        System.out.println(reverse(word));
    }
}

Like others have mentioned, arrays indexes start at 0. So if an array has size 5 for example it has indices 0,1,2,3,4. It does not have an index 5.

就像其他人提到的那样,数组索引从 0 开始。因此,如果数组的大小为 5,例如它的索引为 0、1、2、3、4。它没有索引 5。

For an example of a string with length 5, the code change that I did newWord[--j] = a.charAt(i);will assign to the indices 4,3,2,1,0 in that order.

对于长度为 5 的字符串的示例,我所做的代码更改newWord[--j] = a.charAt(i);将按该顺序分配给索引 4,3,2,1,0。

Regarding getting a good start in Java, I think you could try https://softwareengineering.stackexchange.com/. This site is not meant for that kind of thing.

关于在 Java 中获得良好的开端,我认为您可以尝试https://softwareengineering.stackexchange.com/。这个网站不适合那种事情。

回答by OldCurmudgeon

This is a common difficulty with new Java developers.

这是新 Java 开发人员常见的困难。

The point you are missing is that the last entry in an array is at position a.length-1. Similarly for Strings

您缺少的一点是数组a.length-1的最后一个条目位于 position。同样对于Strings

Here's an improved version to demonstrate.

这是一个改进的版本来演示。

public static String reverse(String a) {
    char[] newWord = new char[a.length()];
    for (int i = 0, j = a.length() - 1; i < a.length(); i++, j--) {
        newWord[j] = a.charAt(i);
    }
    return new String(newWord);
}

回答by AJC24

You're already on the right track with your method. The one thing I will say to you is that you don't need to use an array of characters and then use something like return new String(newWord);. That's overly complicated for beginner Java in my view.

你的方法已经走上了正确的轨道。我要对您说的一件事是您不需要使用字符数组,然后使用类似return new String(newWord);. 在我看来,这对于 Java 初学者来说过于复杂。

Instead, you can create an empty String and just keep appending the characters onto it as you loop through all the characters in the String you want to reverse.

相反,您可以创建一个空字符串,并在循环遍历要反转的字符串中的所有字符时继续将字符附加到该字符串上。

So your forloop, because you're reversing the word, should begin at the end of the word being reversed (ain this case) and work backwards to index position 0 (ie. the start of the word being reversed).

所以你的for循环,因为你正在反转单词,应该从被反转的单词的末尾开始(a在这种情况下),然后向后工作到索引位置 0(即被反转的单词的开头)。

Try this and see if this makes sense to you:

试试这个,看看这对你是否有意义:

public static String reverse(String a) {
    String reversedWord = "";
    for (int index = a.length() - 1; index >= 0; index --) {
        reversedWord += a.charAt(index);
    }
    return reversedWord;  
}

This is, then, starting at the end of a, working backwards one character at a time (hence the use of index --) until we reach a point where indexhas gone beyond the character at index position 0 (the middle condition of index >= 0).

这是,然后,从 的末尾开始,a一次向后处理一个字符(因此使用index --),直到我们到达index超出索引位置 0 处的字符( 的中间条件index >= 0)的点。

At each index position, we are simply taking the character from the aString and appending it onto the reversedWordString.

在每个索引位置,我们只是从aString 中取出字符并将其附加到reversedWordString 上。

Hope this helps! Feel free to ask any other questions if you are stuck on this.

希望这可以帮助!如果您遇到此问题,请随时提出任何其他问题。

回答by Poseydon42

In your forloop, body must be as that newWord[--j] = a.charAt(i);. It's because if the lenght of array is 8, its indexes are 0-7. So we first decrement jand then use it as array pointer.

在您的for循环中, body 必须如此 newWord[--j] = a.charAt(i);。这是因为如果数组的长度为 8,则其索引为 0-7。所以我们先递减j,然后将其用作数组指针。

回答by Master Yi

  public class Test {
        public static String reverse(String a) {
            int size= a.length();//size of string
            char[] newWord = new char[size];//intialize  
            for (int i = size-1,j=0; i >=0 ; i--,j++) {//loop start from 7 to 0
                newWord[j] = a.charAt(i);// and reverse string goes from 0 to 7
            }
            return new String(newWord);
        }

        public static void main(String a[]) {

            String word = "abcdefgh";
            System.out.println(reverse(word));
        }
    }

回答by TruVortex_07

static void reverse {
    String word = "Hello World";
    StringBuilder str = new StringBuilder(word);
    str.reverse();
    System.out.println(str);
}

or you could do

或者你可以做

new StringBuilder(word).reverse().toString()

回答by jishnucodes

public static void main(String[] args) {

    String input = "hello world";
    String output = new String();

    for (int i = input.length() - 1; i >= 0; i--) {
        output = output + input.charAt(i);
    }

    System.out.println(output);

}

回答by Jency

package Reverse;
import java.util.*;

public class StringReverse {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a String:  ");
        String original = input.nextLine();

        String rev = "";// Initialize as Empty String
        for(int i = original.length() - 1 ; i>=0 ; i--){
            rev += original.charAt(i);
        }
        System.out.println("Reverse form: "+rev);
    }
}