如何将String添加到char数组中


public static void main (String[] args) {
char[][] c = {{'a', 'b', 'c'},
{'d', 'e', 'f'}};
show(c);        
}
public static void show (char[][] c) {
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);

我想在每个字母之间留一个空格。我试着写+"在c[i]之后,但是随后我得到这样的警告:";必须显式地将char[]转换为字符串;。我应该如何向数组中添加字符串?提前感谢!

现在您做错的是,您正在打印每个子数组。我不确定我是否正确理解你。但是,如果你想打印2D字符数组的每个char,每个字母之间有空格,那么你应该使用两个for循环来迭代整个2D数组,并像这样打印每个字符:

public static void main(String[] args) {
char[][] c = { { 'a', 'b', 'c' }, { 'd', 'e', 'f' } };
show(c);
}
public static void show(char[][] c) {
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[i].length; j++) {
System.out.print(c[i][j] + " ");
}
}
}

输出:

a b c d e f 

编辑:

要在单独的行中打印每个子阵列,只需更改show方法,如下所示:

public static void show(char[][] c) {
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[i].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println(); // add a println here
}
}

新输出:

a b c 
d e f 

使用Java Streams,您可以做到这一点:

Arrays.stream(c).map(String::valueOf)
.map(i -> i.replace("", " "))
.forEach(System.out::print);

用于输出

a b c  d e f 

或:

Arrays.stream(c).map(String::valueOf)
.map(i -> i.replace("", " "))
.forEach(System.out::println);

输出:

a b c 
d e f 

对于2D字符阵列中的每个字符阵列,我们将其转换为String:

map(String::valueOf)

那么我们添加一个"每个字符串的字符之间:

map(i -> i.replace("", " "))

最后我们打印每个String:的结果

forEach(System.out::println)

您可以使用String.codePoints方法迭代此2d数组中字符的int值,并在它们之间添加空格:

public static void main(String[] args) {
char[][] chars = {{'a', 'b', 'c'}, {'d', 'e', 'f'}};
System.out.println(spaceBetween(chars)); // a b c d e f
}
public static String spaceBetween(char[][] chars) {
return Arrays.stream(chars)
// Stream<char[]> to IntStream
.flatMapToInt(arr -> String.valueOf(arr).codePoints())
// codepoints as characters
// return Stream<Character>
.mapToObj(ch -> (char) ch)
// characters as strings
// return Stream<String>
.map(String::valueOf)
// join characters with
// whitespace delimiters
.collect(Collectors.joining(" "));
}

另请参阅:是否有其他方法可以删除字符串中的所有空白

最新更新