我尝试通过
反转字符串1st convert to a Char[]
2nd reverse the Char[]
3rd convert CHar[] back to String by toString() method
我检查过toString()的输入是“abcd \ 0”,但输出是“[C @ 2e686cea”...
我有两个问题:
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
答案 0 :(得分:5)
要将char[]
转换为String
,您应该使用String.valueOf(char[])
。
char[].toString()
使用Object.toString()
的默认实现,即
getClass()。getName()+'@'+ Integer.toHexString(hashCode())