【问题标题】:How to format a string matrix into x rows and y columns如何将字符串矩阵格式化为 x 行和 y 列
【发布时间】:2018-09-10 17:02:59
【问题描述】:

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

 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

注意:行列需要通过改变rowcolumn变量来改变,即

所以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;
    }

【问题讨论】:

  • 通过new ArrayList&lt;ArrayList&lt;ArrayList&lt;T&gt;&gt;&gt;();,你得到了[[[value, value], [value, value]], [[value, value], [value, value]]]的结构。您如何在其中找到行和列?您不应该使用二维ArrayList 而不是三个吗?
  • 行和列是确定何时在构造函数中创建矩阵对象.. public Matrix(int rows, int columns) { this.rows = rows; this.columns = 列; matrixOne = new ArrayList>>(); for(int i = 0; i >()); for(int j = 0; j ()); } } }
  • 我正在处理你的情况,告诉我,你传递的值总是作为字符串传递的?还是你的列表是字符串?
  • 其实传入的值是通过一个方法(类型其实是泛型的: public void insert(int row, int column, T value) { matrixOne.get(row).get (列).add(值); }
  • 例如; nums.insert(0, 0, "a"); nums.insert(0, 1, "b"); nums.insert(0, 2, "c");

标签: java string arraylist replace format


【解决方案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();

【讨论】:

  • matrixOne.get(i);是一个错误:类型不匹配:无法从 ArrayList> 转换为 ArrayList>
  • 它是一个多数组列表记住即matrixOne
  • 它的工作!更重要的是,您还没有在每一行之后添加标签,那么它就完美了!想法?
  • 目前每个值都用空格隔开?你想要一个标签吗?
  • 好的。添加.replace(" ", "\t") :)
【解决方案2】:

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

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;
 }
}

【讨论】:

    猜你喜欢
    • 2017-07-07
    • 2015-05-18
    • 2017-08-12
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    相关资源
    最近更新 更多