Thursday, February 7, 2013

c# - Merge two strings

Note that this is not concatenating two strings

try
{

   Console.WriteLine("Please enter the first string.");
   string sFirstString = Console.ReadLine().Trim();
   Console.WriteLine();
   Console.WriteLine("Please enter the second string.");
   string sSecondString = Console.ReadLine().Trim();
   Console.WriteLine();


   if (string.IsNullOrEmpty(sFirstString) && !string.IsNullOrEmpty(sSecondString))
   {
       Console.WriteLine("The strings after merging");
       Console.WriteLine(sSecondString);
   }
   else if (!string.IsNullOrEmpty(sFirstString) && string.IsNullOrEmpty(sSecondString))
   {
       Console.WriteLine("The strings after merging");
       Console.WriteLine(sFirstString);
   }
   else if (!(string.IsNullOrEmpty(sFirstString) || string.IsNullOrEmpty(sSecondString)))
   {
       char[] caFirstString = sFirstString.ToCharArray();
       char[] caSecondString = sSecondString.ToCharArray();

       StringBuilder oMergedString = new StringBuilder();

       for (int iIndex = 0; iIndex < (sFirstString.Length >= sSecondString.Length ? sFirstString.Length : sSecondString.Length); iIndex++)
       {
            if (iIndex < (sFirstString.Length >= sSecondString.Length ? sSecondString.Length : sFirstString.Length))
            {
                 oMergedString.Append(caFirstString[iIndex]);
                 oMergedString.Append(caSecondString[iIndex]);
            }
            else if (iIndex < sFirstString.Length)
                 oMergedString.Append(caFirstString[iIndex]);
            else
                 oMergedString.Append(caSecondString[iIndex]);
       }
       Console.WriteLine(oMergedString.ToString());
    }
    else
       Console.WriteLine("The strings cannot be empty.");
}
catch(Exception ex)
{
          Console.WriteLine(ex.Message);
}


Output