Concatenate and convert string array into int

Asked

Viewed 297 times

3

I can’t put together all the numbers in an array, I’m not talking about adding, but concatenating, and converting into an integer. See the example:

ex:

string[] matriz = new string[3];
matriz[0] = "2";
matriz[1] = "5";
matriz[2] = "0";

Do I want to add the numeral 2.5.0 to 250? The example is using an array string, but it could be an array of integers, it makes no difference to me, as long as I can concatenate them and place them in an integer with the value 250.

3 answers

5


The method Join of the object String may be useful.

It takes as parameter:

  • A separator for the final result (in your case it is a string empty since it wants to unite everything in one string only);
  • The array;
  • The index initial;
  • The index final.

In your case I’d be:

var resultadoString = String.Join("", matriz, 0, matriz.Length);

then just take the resultadoString and parse to the whole with the method Parse of the kind int:

var resultadoInt = int.Parse(resultadoString);

I made a fiddle showing you how it would look: https://dotnetfiddle.net/hOvWYo

3

Another option would be the method Concat

int result = int.Parse(string.Concat(matriz));

It is worth remembering that new string[2] makes the array have only 2 elements (0 and 1)

2

In a more 'mathematical' way you can do so:

public class Program
{
    public static void Main()
    {
        int[] matriz = new int[3]; 
        matriz[0] = 2;
        matriz[1] = 5;
        matriz[2] = 0;

        int result = 0;
        for(int i = matriz.Length-1, j = 1; i >= 0; i--, j*=10)
        {
            result = result + (j * matriz[i]);
        }
        Console.WriteLine(result);
    }
}

See working on dotnetFiddle.

As the final value you want to be string, I consider the other answers more appropriate than mine. But the result can then be converted easily using the ToString().

Note that I made some corrections to your code as well.

  1. You were assigning integers in the matrix[], but she was the type string.
  2. Your array only had 2 positions, but you assigned 3 positions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.