Convert int array to string in C#
This post will discuss how to convert int array to string in C#.
1. Using String.Join Method
The String.Join method can be used to concatenate elements of the specified array using the specified separator between each element.
The following example shows how to use String.Join to convert an integer array to a comma-delimited string in C#.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { int[] array = new int[] { 1, 2, 3, 4, 5 }; string s = String.Join(", ", array); Console.WriteLine(s); // 1, 2, 3, 4, 5 } } |
2. Using Array.ForEach Method
If you just need to join together all elements of an array without any separator, you can append each element of the array to a StringBuilder instance using the Array.ForEach method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Text; public class Example { public static void Main() { int[] array = new int[] { 1, 2, 3, 4, 5 }; var builder = new StringBuilder(); Array.ForEach(array, x => builder.Append(x)); string s = builder.ToString(); Console.WriteLine(s); // 12345 } } |
3. Using Enumerable.Aggregate Method
Finally, you can apply an accumulator function over the given integer array sequence with a specified seed as the initial accumulator value. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = new int[] { 1, 2, 3, 4, 5 }; string s = array.Aggregate(string.Empty, (s, i) => s + i); Console.WriteLine(s); // 12345 } } |
That’s all about converting int array to string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)