将带有空格和数字的字符串转换为只含数字的整型数组

4
我想将字符串lotto转换为整数数组。 字符串lotto由1到99之间的某些数字组成,仅由1位和2位数字组成。 (例如:字符串lotto可能看起来像“1 34 5 23 7 89 32 4 10 3 6 5”)。
我尝试通过将字符串转换为char [],然后将char []转换为int []来解决问题。 我将其转换为char []的逻辑是使其可以为int []格式化数字。
以下是我目前的代码:
public static int[] conversion(String lotto)
{
    char[] c = lotto.toCharArray();
    int[] a = new int[c.length];
    for(int i = 0, j = 0; i < c.length; i++)
    {
        if(c[i] != ' ' && c[i+1] != ' ')
        {
            a[j] = c[i] + c[i+1];
            i+=2;
            j++;
        }
        else if(c[i] != ' ' && c[i+1] == ' ')
        {
            a[j] = c[i];
            i++;
            j++;
        }
    }
    return a;
}//end of conversion method

我仍在继续编写程序的其余部分,但我知道 c[i] + c[i+1] 将返回一个ASCII值或不同的int而不是将两个字符组合在一起(所需示例:“3”+“4”=34)。

我该如何解决这个问题?

6个回答

3
如果您不关心转换为字符数组,那么您可以直接使用 .split() 方法。
    String[] nums = lotto.split(" ");
    int[] a = new int[nums.length];
    for(int i = 0; i < a.length; i++)
    {
        a[i] = Integer.parseInt(nums[i]);
    }
    return a;

1
使用字符串的 split 函数,你可以像这样通过空格拆分字符串:
string[] lottoArray = lotto.split(" ");

然后,您可以循环遍历数组并将值放入int数组中:
int[] numbersArray = new int[lottoArray.length];
for (int i = 0; i < lottoArray.length; i++)
    numbersArray[i] = Integer.parseInt(lottoArray[i]);

1

Java 1.8 的乐趣...一行代码:

int[] nums = Pattern.compile("\\s")
   .splitAsStream("1 34 5 23 7 89 32 4 10 3 6 5")
   .mapToInt(Integer::valueOf)
   .toArray();

想要将整型数组排序?仍然只需要一行代码:

int[] nums = Pattern.compile("\\s")
   .splitAsStream("1 34 5 23 7 89 32 4 10 3 6 5")
   .mapToInt(Integer::valueOf)
   .sorted()
   .toArray();

1
我会这样做:


    public static int[] string2array(String s) {
        return util1(s, 0, 0, false);
    }

    private static int[] util1(String s, int n, int l, boolean b) {
        if (s.isEmpty()) {
            return b ? util2(l, n, new int[l + 1]) : new int[l];
        }
        if (Character.isWhitespace(s.charAt(0))) {
            return b ? util2(l, n, util1(s.substring(1), 0, l + 1, false)) : util1(s.substring(1), 0, l, false);
        }
        return util1(s.substring(1), n * 10 + Character.digit(s.charAt(0), 10), l, true);
    }

    private static int[] util2(int idx, int value, int[] array) {
        array[idx] = value;
        return array;
    }

Arrays.toString(string2array("1 34 5 23 7 89 32 4 10 3 6 5")) 的结果是

[1, 34, 5, 23, 7, 89, 32, 4, 10, 3, 6, 5]

http://ideone.com/NCpOQc


1
请使用 String.split
String numbers[]  = lotto.split (" ");

0

将包含数字的String拆分

String str = "1 2 33 64";
String[] numbers = str.split(" ");

创建一个与 String[] 大小相同的 int[] 数组:
int[] array = new int[numbers.length];

循环遍历numbers,解析每个值并将其存储在int[]中:

for(int i = 0; i < numbers.length; i++)
    array[i] = Integer.parseInt(numbers[i]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接