Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string[] to Int[] without losing leading zeros

Tags:

c#

Input:

string param = "1100,1110,0110,0001";

Output:

int[] matrix = new[]
    {
              1,1,0,0,
              1,1,1,0,
              0,1,1,0,
              0,0,0,1
    };

What I did?

First of all I splited string to string[].

string[] resultantArray = param.Split(',');

Created one method, where I passed my string[].

var intArray = toIntArray(resultantArray);

static private int[] toIntArray(string[] strArray)
{        
    int[] intArray = new int[strArray.Length];
    for (int i = 0; i < strArray.Length; i++)
    {
        intArray[i] = int.Parse(strArray[i]);
    }

    return intArray;
}

Issue?

I tried many solutions of SO, but none of them helped me.

Ended up with array without leading zeroes.

like image 552
Bharat Avatar asked Mar 31 '17 13:03

Bharat


Video Answer


2 Answers

  • determine all digits: .Where(char.IsDigit)
  • convert the selected char-digits into integer: .Select(x => x-'0') (this is not as pretty as int.Parse or Convert.ToInt32 but it's super fast)

Code:

string param = "1100,1110,0110,0001";
int[] result = param.Where(char.IsDigit).Select(x => x-'0').ToArray();

As CodesInChaos commented, this could lead to an error if there are other type of Digits within your input like e.g. Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙' where char.IsDigit == true - if you need to handle such special cases you can allow only 0 and 1 in your result .Where("01".Contains)

like image 184
fubo Avatar answered Oct 11 '22 13:10

fubo


You could also remove the commas and convert the result character-wise as follows using Linq.

string param = "1100,1110,0110,0001";
int[] result = param.Replace(",", "").Select(c => (int)Char.GetNumericValue(c)).ToArray();
like image 5
Codor Avatar answered Oct 11 '22 12:10

Codor