我有一个字符串变量,它使用toString()存储获取一个toString的值。
matrixOne = new ArrayList<ArrayList<ArrayList<T>>>();
String output = matrixOne.toString().replace("[", "").replace("]", "");输出以下值:
a, b, c, d, e, f, i, h, g我希望在toString()方法中对它们进行格式化,将它们格式化为新行上的实际行和列,并在值之间加上一个选项卡。示例:
3乘3:
a b c
d e f
i h g注意:行列需要通过更改row column 和column变量(即)来更改。
所以output现在是:a, b, c, d, e, f, g, h, i, j, k, l, m, , n, o, p
2乘3:
a b c d e f g i
j k l m n o p q 实际方法
public String toString() {
String output = matrixOne.toString().replace("[", "").replace("]", "");
return output;
}发布于 2018-04-01 07:06:34
希望这能帮上忙
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();发布于 2018-04-01 15:18:39
Ok,我已经创建了一个方法,该方法可以在矩阵中格式化字符串,其中可以指定行和列:。
public String toString()
{
String output = matrixOne.toString().replaceAll("\\[\\[|\\]|,|\\[|\\]\\]", "");
return FormatMatrix(output, rows, columns);
} 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;
}
}https://stackoverflow.com/questions/49595014
复制相似问题