Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way for the special concatenation of two strings

I want to concatenate two strings in such a way, that after the first character of the first string, the first character of second string comes, and then the second character of first string comes and then the second character of the second string comes and so on. Best explained by some example cases:

    s1="Mark";
    s2="Zukerberg";  //Output=> MZaurkkerberg

if:

    s1="Zukerberg";
    s2="Mark"        //Output=> ZMuakrekrberg

if:

    s1="Zukerberg";
    s2="Zukerberg";  //Output=> ZZuukkeerrbbeerrgg

I've written the following code which gives the expected output but its seems to be a lot of code. Is there any more efficient way for doing this?

public void SpecialConcat(string s1, string s2)
        {
            string[] concatArray = new string[s1.Length + s2.Length];
            int k = 0;
            string final = string.Empty;
            string superFinal = string.Empty;
            for (int i = 0; i < s1.Length; i++)
            {
                for (int j = 0; j < s2.Length; j++)
                {
                    if (i == j)
                    {
                        concatArray[k] = s1[i].ToString() + s2[j].ToString();
                        final = string.Join("", concatArray);
                    }
                }
                k++;
            }
            if (s1.Length > s2.Length)
            {
                string subOne = s1.Remove(0, s2.Length);
                superFinal = final + subOne;
            }
            else if (s2.Length > s1.Length)
            {
                string subTwo = s2.Remove(0, s1.Length);
                superFinal = final + subTwo;
            }
            else
            {
                superFinal = final;
            }
            Response.Write(superFinal);
        }
    }

I have written the same logic in Javascript also, which works fine but again a lot of code.

like image 828
RahulD Avatar asked Nov 28 '22 11:11

RahulD


2 Answers

var s1 = "Mark";
var s2 = "Zukerberg";
var common = string.Concat(s1.Zip(s2, (a, b) => new[]{a, b}).SelectMany(c => c));
var shortestLength = Math.Min(s1.Length, s2.Length);
var result = 
     common + s1.Substring(shortestLength) + s2.Substring(shortestLength);
like image 64
spender Avatar answered Dec 05 '22 01:12

spender


var stringBuilder = new StringBuilder();
for (int i = 0; i < Math.Max(s1.Length, s2.Length); i++)
{
    if (i < s1.Length)
        stringBuilder.Append(s1[i]);

    if (i < s2.Length)
        stringBuilder.Append(s2[i]);
}

string result = stringBuilder.ToString();
like image 32
cuongle Avatar answered Dec 05 '22 02:12

cuongle