取一个String并将其转换为二维数组Java

时间:2017-03-02 03:01:59

标签: java arrays string

我正在开发一个程序,我从用户那里获取输入,输入24长度为String,数字为0-5,每行数重复4次。一个例子就像这个000011112222333344445555。我意识到当我收集用户的号码时我不能在2d int array of [6][4]中拥有它们。这就是我想要的,所以我想要做的是获取该字符串并将每个数字放在该数组中。所以它看起来像[[0,0,0,0],[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4],[5,5,5,5]]。我不知道如何将它们变成这样的数组。我知道字符串是不可变的,所以我不能更改字符串,但我确实认为我可以将字符串转换为char数组,然后将每个值插入到我想要的int数组中。我不知道如何做到这一点任何帮助或指导如何处理这将真的很感激。提前致谢

4 个答案:

答案 0 :(得分:3)

你可以用一个班轮获得你的二维阵列:

int[][] numbers = Arrays.stream("000011112222333344445555".split("(?<=\\G.{4})")).map(s -> (Arrays.stream(s.split("(?<=\\G.{1})")).mapToInt(Integer::parseInt).toArray())).toArray(int[][]::new);

答案 1 :(得分:1)

所以这很容易做到。

lets assume your string is str;

char[] strArr = str.toCharArray();

// numbers is the range like 0 to 5 here.
// repeatCount is how many times its repeating like 4 here.

int arr[][] = new int[numbers][repeatCount];

for(int i = 0; i < numbers; i++){
    for(int j = 0; j < repeatCount; j++){
         arr[i][j] = strArr[i*repeatCount + j]-'0';
    }
}

最后一个预防措施,只有当您的号码是单个数字时,此功能才有效,因为只挑选了一个字符。

答案 2 :(得分:1)

https://www.compilejava.net/上测试如果你有不同的东西,也可以使用:

  

我输入24长度字符串,数字0-5,每个数字是   在行中重复了4次

import java.util.ArrayList;
public class HelloWorld
{

  public static void main(String[] args)
  {
    String s = "00001111222233334444555599";
    ArrayList<ArrayList<Integer>> collection = new ArrayList<ArrayList<Integer>>();
    for (int i = 0; i <= 9; i++){
        collection.add(new ArrayList<Integer>());
    }

    for (int i = 0; i < s.length(); i++){
        int c = Character.getNumericValue(s.charAt(i));        
        collection.get(c).add(c);
    }

    for (int i = 0; i <= 9; i++){
        System.out.println(collection.get(i));
    }

    System.out.println(collection);
  }
}

结果:

[0, 0, 0, 0]
[1, 1, 1, 1]
[2, 2, 2, 2]
[3, 3, 3, 3]
[4, 4, 4, 4]
[5, 5, 5, 5]
[]
[]
[]
[9, 9]
[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5], [], [], [], [9, 9]]

答案 3 :(得分:0)

所以你知道你的字符串必须有4个重复元素,我假设在4次重复之后,接着是一个新值。所以对我来说它似乎是一个N x 4阵列。

因此你可以这样做,我现在会做伪代码来帮助指导你。

int [] [] myArray = new int [str.length / 4] [4]

因为知道如果有“000011112222”我们的总长度是12,我们除以4。12/4是3,我们期待3列。 4是我们拥有的列数,我们知道它只有4个。

之后,在这里,我假设您一个接一个地输入值,没有任何分隔符。我们可以这样做:

    int col = 0;
    int row = 0;
for(i from 0 to string length) {
    if((I+1) % 4 != 0) {
       //keep adding to myArray[row][col]
       //row++
      }
    } else { // so we now hit new numbers
       col++;
       row = 0;
      }
}

所以在这里我试图坚持只有一个for循环。我想用双循环来做它,但是在这种情况下我不知道如何处理它,因为我们最初处理的是一个空数组。

快速编辑,你可以做的一件事,顺便说一句。如此制作2D列表:

List<List<String>> strings = new ArrayList<List<String>>()

int index = 0;
while (index < text.length()) {
    String pattern = text.substring(index, Math.min(index + 4,text.length()));
   List<String> splitPattern = Arrays.asList(pattern.split(""));
   strings.add(splitPattern);
    index += 4;
}

所以这里的逻辑是我们创建一个子串,将它拆分为“”所以在其他词中没有任何东西它只会产生0,0,0,0,因为分隔符不算什么。然后我们将它添加到我们的列表列表中,你可以通过说strings.get(I).get(j);