简体   繁体   中英

Reversing a string java

Working on a problem to reverse a string and I am getting [C@659e0bfd when I try to use the following method to reverse a string. Anyone know what's wrong with this code?

    public static String reverseString(String string) {
    if ((string == null) || (string.length() <= 1)){
        return string;
    }
    char[] charArray = string.toCharArray();
    char[] newString = new char[charArray.length];

    for (int i = 0; i < charArray.length; i++ ){
        newString[i] = charArray[(charArray.length -1)-i];
        }       
    return newString.toString();
}

you are returning array.toString() . if you want to know why it gives C@659e0bfd read this question .

to fix this you can use

return new String(newString);//create string from adding all chars together

public String(char[] chars) is a overloaded constructor of String class which create a new String with array of character

A char[] 's toString() method is not overridden. Which means, it will give back the value provided by Object.toString() method.

You should instead use return new String(newString)

Firstly, all your code, except first if clause can be replaced by only one string:

return new StringBuilder(string).reverse().toString();

Secondly, you don't need nested parentheses in your if clause. So, the method will be the following:

public static String reverseString(String string) {
        if (string == null || string.length() <= 1){
            return string;
        }
        return new StringBuilder(string).reverse().toString();
    }

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