Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I join int[] to a character-separated string in .NET?

Tags:

c#

.net

.net-3.5

I have an array of integers:

int[] number = new int[] { 2,3,6,7 }; 

What is the easiest way of converting these into a single string where the numbers are separated by a character (like: "2,3,6,7")?

I'm using C# and .NET 3.5.

like image 303
Riri Avatar asked Sep 28 '08 13:09

Riri


People also ask

How to Join an array of strings in C#?

The Join() method in C# is used to concatenate all the elements of a string array, using the specified separator between each element.

Which of the following method concatenates the elements of a specified array?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.

How do you join arrays in Java?

To join elements of given string array strArray with a delimiter string delimiter , use String. join() method. Call String. join() method and pass the delimiter string delimiter followed by the string array strArray .


1 Answers

var ints = new int[] {1, 2, 3, 4, 5}; var result = string.Join(",", ints.Select(x => x.ToString()).ToArray()); Console.WriteLine(result); // prints "1,2,3,4,5" 

As of (at least) .NET 4.5,

var result = string.Join(",", ints.Select(x => x.ToString()).ToArray()); 

is equivalent to:

var result = string.Join(",", ints); 

I see several solutions advertise usage of StringBuilder. Someone complains that the Join method should take an IEnumerable argument.

I'm going to disappoint you :) String.Join requires an array for a single reason - performance. The Join method needs to know the size of the data to effectively preallocate the necessary amount of memory.

Here is a part of the internal implementation of String.Join method:

// length computed from length of items in input array and length of separator string str = FastAllocateString(length); fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here {     UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);     buffer.AppendString(value[startIndex]);     for (int j = startIndex + 1; j <= num2; j++)     {         buffer.AppendString(separator);         buffer.AppendString(value[j]);     } } 
like image 87
aku Avatar answered Nov 03 '22 23:11

aku