The string.Join method combines many strings into one. It receives an array or IEnumerable type and a separator string. It places the separator string between every element of the collection in the returned string.
Example program:
using System;
using System.Text;
class Program
{
static void Main()
{
string[] catSpecies = { "Aegean", "Birman", "Main Coon", "Nebulung" };
Console.WriteLine(CombineA(catSpecies));
Console.WriteLine(CombineB(catSpecies));
}
/// <summary>
/// Combine strings with commas.
/// </summary>
static string CombineA(string[] arr)
{
return string.Join(",", arr);
}
/// <summary>
/// Combine strings with commas.
/// </summary>
static string CombineB(string[] arr)
{
StringBuilder builder = new StringBuilder();
foreach (string s in arr)
{
builder.Append(s).Append(",");
}
return builder.ToString().TrimEnd(new char[] { ',' });
}
}
Output :
Aegean,Birman,Main Coon,Nebulung
Aegean,Birman,Main Coon,Nebulung