简体   繁体   中英

Java reverse string method

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!

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

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;

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.

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.

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.

This is a common difficulty with new Java developers.

The point you are missing is that the last entry in an array is at position a.length-1 . Similarly for 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);
}

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.

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 for loop, because you're reversing the word, should begin at the end of the word being reversed ( a in this case) and work backwards to index position 0 (ie. the start of the word being reversed).

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 index has gone beyond the character at index position 0 (the middle condition of index >= 0 ).

At each index position, we are simply taking the character from the a String and appending it onto the reversedWord String.

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

In your for loop, 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 j and then use it as array pointer.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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