I’m trying to mix two strings like this:
string a1 = "123456";
string a2 = "DFEG";
var builder = new StringBuilder();
for (int i = 0; i < a1.Length; i++)
{
builder.Append(a1[i]);
builder.Append(a2[i]);
}
Console.WriteLine(builder.ToString());
I want the output to be "1D2F3E4G56".
It works if both strings are the same lengths, but not if they’re different lengths.
>Solution :
int maxIndex = a1.Length > a2.Length ? a1.Length : a2.Length;
for (int i = 0; i < maxIndex; i++)
{
if(a1.Length > i)
builder.Append(a1[i]);
if(a2.Length > i)
builder.Append(a2[i]);
}