int array to string

Viewed 137253

In C#, I have an array of ints, containing digits only. I want to convert this array to string.

Array example:

int[] arr = {0,1,2,3,0,1};

How can I convert this to a string formatted as: "012301"?

13 Answers

You can simply use String.Join function, and as separator use string.Empty because it uses StringBuilder internally.

string result = string.Join(string.Empty, new []{0,1,2,3,0,1});

E.g.: If you use semicolon as separator, the result would be 0;1;2;3;0;1.

It actually works with null separator, and second parameter can be enumerable of any objects, like:

string result = string.Join(null, new object[]{0,1,2,3,0,"A",DateTime.Now});

This is a roundabout way to go about it its not much code and easy for beginners to understand

    int[] arr = {0,1,2,3,0,1};
    string joined = "";
    foreach(int i in arr){
        joined += i.ToString();
    }
    int number = int.Parse(joined);
    
// This is the original array
int[] nums = {1, 2, 3};

// This is an empty string we will end up with
string numbers = "";

// iterate on every char in the array
foreach (var item in nums)
{
    // add the char to the empty string
    numbers += Convert.ToString(item);
}

// Write the string in the console
Console.WriteLine(numbers);
Related