using System;
class Program
{
static void Main()
{
string[] arr = { "one", "two", "three" };
// "string" can be lowercase.
Console.WriteLine(string.Join(",", arr));
// ... "String" can be uppercase.
Console.WriteLine(String.Join(",", arr));
}
}
Output
one,two,three
one,two,three
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
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a List of three strings.
var list = new List<string>() { "cat", "dog", "rat" };
// Join the strings from the List.
string joined = string.Join<string>("*", list);
// Display.
Console.WriteLine(joined);
}
}
Output
cat*dog*rat
static string CombineA(string[] arr)
{
return string.Join(",", arr);
}
static string CombineB(string[] arr)
{
var builder = new System.Text.StringBuilder();
foreach (string s in arr)
{
builder.Append(s).Append(",");
}
return builder.ToString(); // Has ending comma [difference]
}
Results
string.Join: 157 ms [faster]
StringBuilder Append method: 270 ms