如何将字符串矩阵格式化为x行和y列

时间:2018-04-01 05:11:46

标签: java string arraylist replace format

我有一个字符串变量,存储使用toString()获取ArrayList的值。

component

输出打印以下值:

 matrixOne = new ArrayList<ArrayList<ArrayList<T>>>();

 String output = matrixOne.toString().replace("[", "").replace("]", "");

我希望它们在toString()方法中进行格式化,以在新行上格式化为实际的行和列,并在值之间使用制表符。例如:

3 by 3:

a, b, c, d, e, f, i, h, g

注意:行列需要通过更改a b c d e f i h g row变量来更改,例如

所以column现在是:output

2 by 3:

a, b, c, d, e, f, g, h, i, j, k, l, m, , n, o, p

实际方法

a  b  c  d  e  f  g  i
j  k  l  m  n  o  p  q 

2 个答案:

答案 0 :(得分:1)

希望这可以提供帮助

StringBuilder sb = new StringBuilder();
for (int i = 0, rowCount = matrixOne.size(); i < rowCount; i++) {
    ArrayList<ArrayList<T>> row = matrixOne.get(i);
    sb.append(row.toString()
        .replaceAll("\\[\\[|\\]|,|\\[|\\]\\]", "")
        .replace(" ", "\t"));
    sb.append("\n");
}
return sb.toString();

答案 1 :(得分:0)

好的,我已经创建了一个方法,可以在矩阵中格式化字符串,您可以在其中指定行和列:

 public static String FormatMatrix(String str, int rows, int columns) {
 try {
  String[][] matrix = new String[rows][columns];
  String[] arr = str.split("\\s*,\\s*");

  int k = 0;
  int s = arr.length;

  for (int i = 0; i < rows; ++i) {
   for (int j = 0; j < columns; ++j) {
    matrix[i][j] = (k < s) ? arr[k] : "*";
    ++k;
   }
  }

  String append = "", result;

  for (int i = 0; i < rows; ++i) {
   append += "|\t";
   for (int j = 0; j < columns; ++j) {
    append += matrix[i][j] + "\t";
   }
   append += "|\n";
  }
  result = append;
  return result;

 } catch (Exception e) {
  return null;
 }
}
X = np.arange(9).reshape(3,3)
     array([[0, 1, 2],
            [3, 4, 5],
            [6, 7, 8]])