Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda