Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mix 2 strings that do not have the same length?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading