有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何打印相邻的2D数组矩阵的格式化字符串

我得到一个字符串,并将其转换为二维数组。 给定的字符串是*23**23412341_3*

我编写的将其转换为二维数组的代码是:

public String[][] str2arr(String str)
{
    String[] rows = str.split("(?<=\\G....)"); // split the string at every 4th character
    String[][] matrix = new String[rows.length][];
    int r = 0;
    for (String row : rows)
    {
        matrix[r++] = row.split("(?<=\\G.)"); // split each of the string of each row
    }
    return matrix;
}

这段代码给出的结果类似于[[*, 2, 3, *], [*, 2, 3, 4], [1, 2, 3, 4], [1, _, 3, *]]

我把它格式化成

*23*
*234
1234
1_3*

使用此代码:

public void printMatrix(String[][] x)
{
    for (int i=0; i < x.length; i++)
    {
        for (int j=0; j<x[0].length; j++)
        {
            System.out.print(x[i][j] + "");
        }
        System.out.print("\n");
    }
}

但现在我得到了第二个字符串,需要将其显示在矩阵的一侧(其右侧),而不是第一个矩阵的底部

*23* *23*
*234 *234
1234 1234
1_3* 1_3*

这可能吗?如果没有,为什么不呢?我如何更新这些代码,以实现我的目标


共 (2) 个答案

  1. # 1 楼答案

    您可以绑定字符串[][]x,然后显示绑定的x

    public String[][] cbind(String[][] x1, String[][] x2) {
    
    
            String[][] output = new String[x1.length][x2[0].length +x2[0].length];
    
            for (int i = 0; i < x1.length; i++) {
    
                for (int j = 0; j < x1[0].length; j++) {
    
                    output[i][j] = x1[i][j];
    
                }
    
                for (int j = 0; j < x2[0].length; j++) {
    
                    output[i][j + x1[0].length] = x2[i][j];
                }
    
            }
    
            return output;
        }
    
  2. # 2 楼答案

    你不能按你的要求去做。但是你可以把两个矩阵并排打印出来

    创建一个包含所有矩阵的类。这将假定所有矩阵的维数相同:

    public class MatrixHolder {
        private List<String[][]> matrices = new ArrayList<>();
    
        public void addMatrix(String[][] matrix) {
            matrices.add(matrix);
        }
    
        public void printMatirces() {
            for(int i = 0; i < matrices.get(0).length; i++) {
                for(int j = 0; j < matrices.size(); j++) {
                    System.out.print(rowString(matrices.get(j)[i]) + " ");
                }
                System.out.println();
            }
        }
    
        private static String rowString(String[] row) {
            StringBuilder sb = new StringBuilder();
            for(String s : row)
                sb.append(s);
            return sb.toString();
        }
    }
    

    下面是一个如何使用它的示例:

    String input = "*23**23412341_3*";
    
    MatrixHolder mh = new MatrixHolder();
    mh.addMatrix(str2arr(input));
    
    mh.printMatirces();
    System.out.println();
    
    mh.addMatrix(str2arr(input));
    
    mh.printMatirces();
    

    输出:

    *23* 
    *234 
    1234 
    1_3* 
    
    *23* *23* 
    *234 *234 
    1234 1234 
    1_3* 1_3*