java - 字符串转int数组

标签 java string int

我有以下字符串代码

[444398, 1]
[111099, 0]
[188386, 2]
[149743, 0]

我想创建一个二维数组,其中每个数字都是一个 int。 例如,

int[][] temp = new int[4][2]

我正在尝试使用

String challengetemp = Arrays.toString(Challenge.challenge(players[0], players[1]));
challengeList[i][i] = Integer.parseInt(challengetemp.split("\\|",-1));

但对于初学者来说,ParseInt 会出现类型不匹配并导致错误。

我需要能够随后以整数形式访问数组中的信息

最佳答案

我会利用StringTokenizer做这样的事情。

    String str = "[444398, 1][111099, 0][188386, 2][149743, 0]";

        str = str.replace("[","");
        str = str.replace("]","|");

        int arr[][] = new int[4][2];
        StringTokenizer token = new StringTokenizer(str,"|");
        for(int i=0;i<4;i++)
        {
            StringTokenizer nextToken = new StringTokenizer(token.nextToken(),",");
         for(int j=0;j<2;j++)
          {
            String tokenValue = nextToken.nextToken();
            if(tokenValue.contains("|"))
            {
                tokenValue.replace("|", "");
            }
            arr[i][j]= Integer.parseInt(tokenValue.trim());
          }
        }

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.println(arr[i][j]);
            }
        };

并且您必须对循环进行一些修改,以便它可以根据需要将尽可能多的 String 解析为 int 数组。

关于java - 字符串转int数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17621568/

相关文章:

java - 在 Java 中先按长度排序数组然后按字母顺序排序

c - 在纯 c 中查找字符串 (char*) 中的 int

Java 到 C++ 异或加密失败

java - Android,Java - AutocompleteTextView列表显示在编辑框下

VB.NET IsNot 用于字符串比较

c++ - 获取字符串的最后一行

php - 使用 PHP 从 MySQL 数据库中选择可能相关的项目(如 : for 'orange' , 给出 'bread')

c# - 为什么我可以安全地转换为 int 而不能转换为 int?

java - 将 int char 转换为 int 而不改变 java 中的值

java - RPi 3 上的 Eclipse Kura 安装失败,错误代码为 "could not bind a reference or component"