none
C# string index concacinate RRS feed

  • Question

  • hello, i need help in combining two stings indexes`

    for examble 

    string strs1 = "Hello";

    string str2 = "World";

    i need the output to be like so : HWeolrllod 

    meaning adding the indexes from each string continually but i do not know what is the perfect method for it.

    Sunday, November 12, 2017 3:52 PM

All replies

  • Try this:

    string str1 = "Hello";
    string str2 = "World";
    string result = string.Concat( str1.Zip( str2, ( c1, c2 ) => string.Concat( c1, c2 ) ) );
    Console.WriteLine( result );

     

    If a string is longer, its tail is not included.


    Sunday, November 12, 2017 4:37 PM
  • I'd do it like this (it will include all of both strings, even if one is longer than the other:

    string strs1 = "Hello";
    string str2 = "WorldAgain";
    int max = Math.Max(strs1.Length, str2.Length);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < max; i++)
    {
        if (i < strs1.Length)
            sb.Append(strs1.Substring(i, 1));
        if (i < str2.Length)
            sb.Append(str2.Substring(i, 1));
    }
    string result = sb.ToString();
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, November 12, 2017 4:44 PM
    Moderator
  • Hello, 

    Many thanks for the help. 

    so just to make sure that i understand every bit of the code.

    so you used the .Append() method so if there will be rest of one of the strings characters left it will append it at the end of the concatenated strings, am I right? 

    second, 

    what if i have the strings of the same length will I use different method or just use the append , because even if i used the Append() method it won't make sense ! 

    Many thanks for the effort. 

    Wednesday, November 22, 2017 10:33 PM
  • >>so you used the .Append() method so if there will be rest of one of the strings characters left it will append it at the end of the concatenated strings, am I right? <<

    Yes, that's correct.

    >>what if i have the strings of the same length will I use different method or just use the append , because even if i used the Append() method it won't make sense ! <<

    No, you don't have to use a different method. That will work for any situation. What do you mean it won't make sense?


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Thursday, November 23, 2017 2:22 AM
    Moderator