In previous article, I mentioned C# Comments with example (Single or Multi-line) but in this article, I have mentioned how we can get comma-seperated String from int Array or string array in C# with an example.
Get String from Int Array in C#
We can use string.Join()
method to convert int array to comma-seperated string in C#, here is the complete C# Console application example
using System;
namespace StringFromArray
{
internal class Program
{
static void Main(string[] args)
{
int[] intArray = { 1, 2, 3, 4 , 5};
var str = String.Join(",", intArray); //will give comma-seperated string
Console.WriteLine(str);
}
}
}
Here is the output
1,2,3,4,5
Using StringBuilder
If you don't want to add any seperator when converting array to string, you can use this option
using System;
using System.Text;
namespace StringFromArray
{
internal class Program
{
static void Main(string[] args)
{
int[] intArray = { 1, 2, 3, 4 , 5};
var builder = new StringBuilder();
Array.ForEach(intArray, x => builder.Append(x));
Console.WriteLine(builder.ToString());
}
}
}
Output:
12345
Get String from String Array in C#
You can use same methods like string.Join()
or StringBuilder
or using Linq
to get string from string array in C#, here is console application example.
using System;
using System.Linq;
using System.Text;
namespace StringFromArray
{
internal class Program
{
static void Main(string[] args)
{
//using string.join
string[] fruits = { "Apple", "Mango", "Banana", "Grapes" };
var str = String.Join(",", fruits);
Console.WriteLine(str);
//using stringbuilder
var builder = new StringBuilder();
Array.ForEach(fruits, x => builder.Append(x+ " "));
Console.WriteLine(builder.ToString());
//using linq
var str2 = fruits.Aggregate("", (s, i) => s + i.ToString()+ " ");
Console.WriteLine(str2);
}
}
}
Output:
Apple,Mango,Banana,Grapes
Apple Mango Banana Grapes
Apple Mango Banana Grapes
In the above code, we have also use Linq(var str2 = fruits.Aggregate("", (s, i) => s + i.ToString()+ " ")
) method to convert string array to string in C#.
In linq and stringbuilder method, we are seperating string array using " "(space) instead of comma (",").
You may also like to read:
How to define C# multiline string literal?
Switch case multiple conditions in C#
Encrypt and Decrypt files in C#
Exception handling in C# (With try-catch-finally block details)
Int to Enum or Enum to Int in C#
Generate Random alphanumeric strings in C#
Various star pattern program in c#
Remove Duplicates from Array in C#
Get Character to ASCII value in C#