- using Concat() method of String class
- using Join() method of String class
- using StringBuilder class
- using Concatenation Operator (+)
I wrote a class(StringJoin) which is implemented all of the above points,
public class StringJoin
{
public StringJoin() { }
public string JoinUsingConcat(string firstItem, string secondItem)
{
return string.Concat(values: new[] { firstItem, secondItem });
}
public string JoinUsingConcat(string[] items)
{
return string.Concat(values: items);
}
public string JoinUsingJoin(string firstItem, string secondItem)
{
return string.Join(separator: string.Empty, value: new[] { firstItem, secondItem });
}
public string JoinUsingJoin(string[] items)
{
return string.Join(separator: string.Empty, value: items);
}
public string JoinUsingBuilder(string firstItem, string secondItem)
{
StringBuilder builder = new StringBuilder();
builder.Append(value: firstItem).Append(value: secondItem);
return builder.ToString();
}
public string JoinUsingBuilder(string[] items)
{
StringBuilder builder = new StringBuilder();
foreach (string item in items)
builder.Append(value: item);
return builder.ToString();
}
public string JoinUsingConcatenationOperator(string firstItem, string secondItem)
{
return firstItem + secondItem;
}
public string JoinUsingConcatenationOperator(string[] items)
{
string result = string.Empty;
foreach (string item in items)
result += item;
return result;
}
}
and a Test class to test above code as below,
class Program
{
static void Main(string[] args)
{
string[] items = new string[] { "One-", "Two-", "Three" };
StringJoin stringJoin = new StringJoin();
Console.WriteLine("Result : {0}", stringJoin.JoinUsingConcat("One-", "Two"));
Console.WriteLine("Result : {0}", stringJoin.JoinUsingConcat(items));
Console.WriteLine("Result : {0}", stringJoin.JoinUsingJoin("One-", "Two"));
Console.WriteLine("Result : {0}", stringJoin.JoinUsingJoin(items));
Console.WriteLine("Result : {0}", stringJoin.JoinUsingBuilder("One-", "Two"));
Console.WriteLine("Result : {0}", stringJoin.JoinUsingBuilder(items));
Console.WriteLine("Result : {0}", stringJoin.JoinUsingConcatenationOperator("One-", "Two"));
Console.WriteLine("Result : {0}", stringJoin.JoinUsingConcatenationOperator(items));
Console.ReadKey();
}
}
and the output of the code is as below,
There would be some other ways to join .Net string. Happy to learn others.
No comments:
Post a Comment