在Java中,输出`char`类型数组的内容可以通过以下几种方法:
直接输出数组名
char[] chs = "HelloWorld1234".toCharArray();
System.out.println(chs);
输出结果:`[H, e, l, l, o, W, o, r, l, d, 1, 2, 3, 4]`
使用`Arrays.toString()`方法
import java.util.Arrays;
char[] chs = "HelloWorld1234".toCharArray();
System.out.println(Arrays.toString(chs));
输出结果:`[H, e, l, l, o, W, o, r, l, d, 1, 2, 3, 4]`
使用`for`循环遍历输出
char[] chs = "HelloWorld1234".toCharArray();
for (char c : chs) {
System.out.print(c);
}
输出结果:`HelloWorld1234`
使用`printf`方法
char[] chs = "HelloWorld1234".toCharArray();
for (int i = 0; i < chs.length; i++) {
System.out.printf("%c", chs[i]);
}
输出结果:`HelloWorld1234`
使用`System.out.println`方法
char[] chs = "HelloWorld1234".toCharArray();
System.out.println(new String(chs));
输出结果:`HelloWorld1234`
注意,`char`类型数组在Java中通常被当作字符串处理,因此可以直接使用`System.out.println`方法输出其内容,而无需显式调用`toString()`方法。这是因为`PrintStream`类重载了`println`方法,可以直接接受`char[]`类型的参数