Java 如何将二维字符串数组打印为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2397535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:01:33  来源:igfitidea点击:

How to print two dimensional array of strings as String

javastringmultidimensional-array

提问by sasklacz

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

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

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();

How can I print a 2D array?

如何打印二维数组?

采纳答案by Hyman

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(']');
}

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

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

IMPORTANT2:since in this case you plan to append many things to the StringBufferit'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.

重要 2:由于在这种情况下您计划将许多内容附加StringBuffer到估计容量以避免在附加期间多次分配和重新定位数组,您可以计算多维数组的大小乘以平均字符长度您计划追加的元素。

回答by Felix Kling

Two forloops:

两个for循环:

for (int i=1; i<res.length; i++) {
    for (int j=1; j<res[i].length; j++) {
        result.append(separator);
        result.append(res[i][j]);
    }
}

回答by Pindatjuh

public static <T> String to2DString(T[][] x) {
    final String vSep = "\n";
    final String hSep = ", ";
    final StringBuilder sb = new StringBuilder();

    if(x != null)
    for(int i = 0; i < x.length; i++) {
        final T[] a = x[i];
        if(i > 0) {
            sb.append(vSep);
        }
        if(a != null)
        for(int j = 0; j < a.length; j++) {
            final T b = a[j];
            if(j > 0) {
                sb.append(hSep);
            }
            sb.append(b);
        }
    }
    return sb.toString();
}

回答by Robert Christie

The Arraysclass defines a couple of useful methods

数组类定义了几个有用的方法

  • Arrays.toString- which doesn't work for nested arrays
  • Arrays.deepToString- which does exactly what you want

 

 

String[][] aastr = {{"hello", "world"},{"Goodbye", "planet"}};
System.out.println(Arrays.deepToString(aastr));

Gives

  [[hello, world], [Goodbye, planet]]

回答by Sil

public static void main(String[] args) {

    String array [] [] = {
        {"*","*", "*", "*", "*", "*"},
        {"*"},
        {"*"},
        {"*"},
        {"*","*", "*", "*", "*", "*"},
        {"*"},
        {"*"},
        {"*"},
        {"*"},
        {"*"}};


    for (int row=0; row<array.length;row++) {

        for (int column = 0; column < array[row].length; column++) {
            System.out.print(array[row][column]);
        }
        System.out.println();
    }
}