C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
CharCombine: We call this method by passing it 4 chars. We can adapt the code to be used on any number of chars.
Tip: It is contained in a static class and is a static method, which is ideal for a utility method such as this. It does not save state.
StaticInfo: CharCombine allocates a new char array with 4 elements. Then, it assigns slots at indices 0 to 3 to the four parameter chars.
Finally: The new string(char[]) constructor is invoked in the return statement, which builds the string from the char buffer we created.
String ConstructorReturnC# program that combines four chars
using System;
class CharTool
{
/// <summary>
/// Combine four chars.
/// </summary>
public static string CharCombine(char c0, char c1, char c2, char c3)
{
// Combine chars into array
char[] arr = new char[4];
arr[0] = c0;
arr[1] = c1;
arr[2] = c2;
arr[3] = c3;
// Return new string key
return new string(arr);
}
}
class Program
{
static void Main()
{
char a = 'a';
char b = 'b';
char c = 'c';
char d = 'd';
char e = 'e';
// Use CharCombine method
Console.WriteLine(CharTool.CharCombine(a, b, c, d));
Console.WriteLine(CharTool.CharCombine(b, c, d, e));
}
}
Output
abcd
bcde
Varibles used in benchmarks: C#
char a = 'a';
char b = 'b';
char c = 'c';
char d = 'd';
Code benchmarked in loops: C#
// Custom method
string s1 = CharTool.CharCombine(a, b, c, d); // [above]
string s2 = CharTool.CharCombine(d, c, b, a);
// Concatenation
string s1 = a.ToString() + b.ToString() + c.ToString() + d.ToString();
string s2 = d.ToString() + c.ToString() + b.ToString() + a.ToString();
Combine chars benchmarks:
CharCombine method: 520 ms
Char concat: 1887 ms