Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a String with spaces and numbers to an int array with just numbers

I want to convert String lotto int an integer array. String lotto is composed of a certain amount of numbers between 1 and 99 and is only composed of 1 and 2 digit numbers. (Example: String lotto might look like "1 34 5 23 7 89 32 4 10 3 6 5".)

I am trying to solve the problem by converting the String to char[] and then the char[] to an int[]. My logical behind converting it to the char[] is make it possible to format the numbers for the int[].

Here is what I have so far:

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

I am still working on the rest of the program but I know that c[i] + c[i+1] with return an ASCII value or a different int rather than combining the two chars together (Example of what I want: '3' + '4' = 34.)

How do I fix this problem?

like image 804
pirisu Avatar asked Mar 19 '23 01:03

pirisu


2 Answers

If you don't care about converting to a character array then you could just use the .split() method

    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;
like image 161
jhillkwaj Avatar answered Mar 20 '23 15:03

jhillkwaj


Try using String.split

String numbers[]  = lotto.split (" ");
like image 34
Scary Wombat Avatar answered Mar 20 '23 15:03

Scary Wombat