Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

  • 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)

about 4 years ago · Santiago Trujillo Report

0

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();
about 4 years ago · Santiago Trujillo Report

0

yet another way to do this

static private IEnumerable<int> toIntArray(string[] strArray)
{
    foreach (string str in strArray)
    {
        foreach (char c in str)
        {
            yield return (int)char.GetNumericValue(c);
        }
    }
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!