如何将字符串的二维数组打印为String [英] How to print two dimensional array of strings as String

查看:140
本文介绍了如何将字符串的二维数组打印为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何对一维字符串数组执行toString方法,但是如何打印二维数组?使用1D时,我是这样进行的:

I know how to do the toString method for one dimensional arrays of strings, but how do I print a two dimensional array? With 1D I do it this way:

public String toString() {
    StringBuffer result = new StringBuffer();
    res = this.magnitude;

    String separator = "";
    if (res.length > 0) {
        result.append(res[0]);
        for (int i=1; i<res.length; i++) {
            result.append(separator);
            result.append(res[i]);
        }
    }
return result.toString();

如何打印2D阵列?

推荐答案

您只需对元素进行两次迭代:

You just iterate twice over the elements:

StringBuffer results = new StringBuffer();
String separator = ","
float[][] values = new float[50][50];

// init values

for (int i = 0; i < values.length; ++i)
{
  result.append('[');
  for (int j = 0; j < values[i].length; ++j)
    if (j > 0)
      result.append(values[i][j]);
    else
      result.append(values[i][j]).append(separator);
  result.append(']');
}

重要提示: StringBuffer也很有用,因为您可以链接操作,例如:buffer.append(..).append(..).append(..),因为它返回对self的引用!如果可以的话,使用晕厥糖.

IMPORTANT: StringBuffer are also useful because you can chain operations, eg: buffer.append(..).append(..).append(..) since it returns a reference to self! Use synctactic sugar when available..

重要2::由于在这种情况下,您计划将许多内容附加到StringBuffer,因此最好估算一下避免在附加过程中多次分配和重新定位数组的容量,因此您可以进行计算多维数组的大小乘以您计划附加的元素的平均字符长度.

IMPORTANT2: since in this case you plan to append many things to the StringBuffer it's good to estimate a capacity to avoid allocating and relocating the array many times during appends, you can do it calculating the size of the multi dimensional array multiplied by the average character length of the element you plan to append.

这篇关于如何将字符串的二维数组打印为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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