문제

Hi I'm writing a test program to reverse a string. When I convert the character array to a string using the toString() method, I get the wrong output. When I try to print the array manually using a for loop without converting it to a string the answer is correct. The code I've written is shown below:

import java.util.*;
public class stringManip {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    String str = "This is a string";
    System.out.println("String=" +str);
    //reverse(s);

    char[] c = str.toCharArray();
    int left = 0;
    int right = str.length() - 1;
    for (int i = 0; i < (str.length())/2; i++)
    {
        char temp = c[left];
        c[left++] = c[right];
        c[right--] = temp;
    }
    System.out.print("Reverse="+c.toString());


    }
}

I should get the reverse of the string I entered, instead the output am getting is:

String=This is a string

Reverse=[C@45a1472d

Is there something am doing wrong when using the toString() method? Any help is appreciated. Thank you.

도움이 되었습니까?

해결책

Arrays don't override the toString() method. What you're seeing is thus the output of the default Object.toString() implementation, which contains the type of the object ([C means array of chars) followed by its hashCode.

To construct a String from a char array, use

new String(c)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top