1

文字列を逆にしようとしています

1st convert to a Char[]
2nd reverse the Char[]
3rd convert CHar[] back to String by toString() method

toString() の入力が "abcd\0" であることを確認しましたが、出力は "[C@2e686cea" です ...

2 つの質問があります。

1. why toString() output this
2. what's the best way to process String? convert to char[] or using StringBuffer?

これが私のコードです:

public class TestBench_1_2 {
    public static String reverseCStr (String str) { 
        if (str == null) return str;
        char[] cArray = str.toCharArray();
        int len = str.length();
        char temp = '\0';
        for (int i = 0; i < (Math.floor((len-1)/2)); ++i) {
            temp = cArray[i];
            cArray[i] = cArray[len-2-i];
            cArray[len-2-i] = temp;
        }
//      String result = new String(cArray);
        String result = cArray.toString();
        return  result;
    }

    public static void main (String[] args) {
        String[] testStr = {"abcd\0", "abcde\0", "123\0", "ab1p4\0", null};
        System.out.printf("Test Strings: \t\t Reverse Result: \n");
        String temp = null;
        for (String str : testStr) {
            System.out.printf("%s \t\t\t %s\n", str, reverseCStr(str));
        }
    }
}

出力は次のとおりです。

Test Strings:            Reverse Result: 
abcd                     [C@2e686cea
abcde                    [C@8e43b44
123                      [C@3feef1eb
ab1p4                    [C@604c9c17
null                     null
4

1 に答える 1

5

を に変換するchar[]にはString、 を使用する必要がありますString.valueOf(char[])

char[].toString()は、他のすべての配列実装と同様に、 のデフォルトの実装を使用しますObject.toString()

getClass().getName() + '@' + Integer.toHexString(hashCode())

于 2013-10-27T15:17:07.023 に答える