【问题标题】:1D -> 2D String array conversion一维 -> 二维字符串数组转换
【发布时间】:2015-01-21 11:44:36
【问题描述】:

是否可以从一维字符串数组创建一个二维数组,例如 3x4 一个?例如,

String[] animals = {"Abyssinian", "Beagle", "Bear", "Cassowary", "Chesapeake Bay Retriever", 
                    "Common Buzzard", "Dunker", "Eskimo Dog", "Ferret", 
                    "Glow Worm", "Jellyfish", "Komodo Dragon"};

应转换为String[][]

【问题讨论】:

    标签: java arrays type-conversion multidimensional-array


    【解决方案1】:

    是的,这是可能的。例如(你必须根据你想要达到的确切结果来定制它)

    public static String[][] convertTo2D( String[] arr, int x, int y ) {
      //if ( arr.length != x * y ) throw new IllegalArgumentException();
      String[][] ret = new String[x][y];
      for( int i_x = 0, i = 0; i_x < x; i_x++ )
        for( int i_y = 0; i_y < y; i_y++, i++ ) {
          //if ( i >= arr.length ) return ret;
          ret[i_x][i_y] = arr[i];
        }
      return ret;
    }
    

    【讨论】:

    • 您缺少退货声明。
    【解决方案2】:

    这个例子展示了一种从数组中加载矩阵的方法。

    String[] animals = {"Abyssinian", "Beagle", "Bear", "Cassowary",
        "Chesapeake Bay Retriever", "Common Buzzard", "Dunker", "Eskimo Dog",
        "Ferret", "Glow Worm", "Jellyfish", "Komodo Dragon"};
    
    int matrix[][] = new String[3][4];
    int apos = 0;
    
    for (int x=0; x < 3; x++) {
        for (int y=0; y<4; y++) {
            matrix[x][y] = animals[apos];
            apos = apos + 1;
        }
    }
    

    您也可以将动物数组作为矩阵访问,例如您想要使用 animal[i][j]:

    animal[ i*4 + j ]
    

    【讨论】:

    • 这与我一小时前提供的通用解决方案有何不同? OP 在回答 Should it work only for 12 elements and 3x4 result? 时明确表示 - “我正在寻找更通用的解决方案。”另外,apos = apos + 1; 让我想知道您以前的编码经验...
    • @vaxquis:第一,当我说要接听电话并打断我时,我没有看到您的解决方案,我没有看到任何警告,对此我很抱歉。对于代码体验的事情,你可能会参加私人比赛,但为了争论,让我们在 Scala、Haskel Erlang中进行,那么你可能想知道你喜欢什么。
    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多