Following program is given in the above website. Please explain the reasons for the followings:
-In order to cast builder why it is not correct to use (string)builder.
-TrimEnd({ ',' }) is doing the job instead of TrimEnd(new char[] { ',' })
Problem is highlited.
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));
Console.Read();
}
///
/// Combine strings with commas.
///
static string CombineA(string[] arr)
{
return string.Join(",", arr);
}
///
/// Combine strings with commas.
///
static string CombineB(string[] arr)
{
StringBuilder builder = new StringBuilder();
foreach (string s in arr)
{
builder.Append(s).Append(",");
}
return builder.ToString().TrimEnd(new char[] { ',' });
}
}
/*
Aegean,Birman,Main Coon,Nebulung
Aegean,Birman,Main Coon,Nebulung
*/
Posted Jan 23, 2014, 4:19 PM
VulpesPosted Jan 23, 2014, 11:07 AM
However, it doesn't support such an conversion and so you have to use the ToString() method to convert a StringBuilder instance to a string.
The String.TrimEnd method takes a char 'params' array as its argument.
This means that you can either pass it a char array or you can pass one or more individual char arguments. If there's more than one, then the arguments should be separated by commas.