如何将String添加到char数组? [英] How do I add String to a char array?

查看:75
本文介绍了如何将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 []明确转换为字符串".我应该如何将一个字符串添加到我的数组?预先感谢!

I want a space between each letter. I tried to write + " " after c[i] but then I get this warning: "Must explicitly convert the char[] to a String". How I am supposed to add a string to my array? Thanks in advance!

推荐答案

现在您做错了,您正在打印每个子数组.我不确定我是否正确理解您.但是,如果要打印2D char数组的每个 char ,并且每个字母之间都有空格,则应使用两个 for 循环遍历整个2D数组并打印每个像这样的字符:

Right now what you are doing wrong is, you are printing each sub-array. I'm not sure if I understood you correctly. But if you want to print each char of your 2D char array with space between each letter, then you should use two for loops to iterate over the whole 2D array and print each char like this:

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 方法,如下所示:

To print each sub-array in a seperate line, simply change the show method like this:

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 

这篇关于如何将String添加到char数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆