locked
Convert string into a specific format using Console Application in C# Dot Net RRS feed

  • Question

  • User607530938 posted

    Hello All,

    I have String I want to convert it into a Specific format dyanamicaly using Console Apllication in C# Dot Net.

    eg. Hello = hoell

    Hybernate = heytbaenr 

    Logic is first Character then last char after that 2nd char then 2nd last after that 3rd char and then 3rd last............ 

    I need Console Program in C# for this Logic.

    Thanks In advance....

    Saturday, June 8, 2013 1:36 AM

Answers

  • User-1910946339 posted

    There is probably a more efficeient way but since this feels like homework I will just present this

    result = String.Join(String.Empty, inStr.Zip(inStr.Reverse(),(c,d)=>c.ToString()+d.ToString())).Substring(0, inStr.Length);

    If this is homework then I suspect you will not be able to understand what is happening and so you could not hand it in.  If this is not homework and you cannot understand what is happening then please let us know what the business need is that you are satisfying and we can try to help you.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 8, 2013 2:25 AM

All replies

  • User-1910946339 posted

    There is probably a more efficeient way but since this feels like homework I will just present this

    result = String.Join(String.Empty, inStr.Zip(inStr.Reverse(),(c,d)=>c.ToString()+d.ToString())).Substring(0, inStr.Length);

    If this is homework then I suspect you will not be able to understand what is happening and so you could not hand it in.  If this is not homework and you cannot understand what is happening then please let us know what the business need is that you are satisfying and we can try to help you.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 8, 2013 2:25 AM
  • User607530938 posted

    Hello Paul,

    First I want to say Thanks for Reply, This was puzzle which is asked to me in Interview that time I was not getting proper Output.

    Again Thanks for ur Reply.

    Saturday, June 8, 2013 2:58 AM
  • User-1910946339 posted

    Fair enough.

    What the code does is uses the linq Zip operator to join two sequences together.  The two sequences are the initial string (hello) and its reverse (olleh).  Zip does the work of taking one character from each input and processing the pair.  It is just a matter of adding the two characters together (after converting each of them to a one character string).  This gives strings which are two characters long ("ho", "el", "ll", "le", "oh").  The String.Join then joins them all up ("hoelllleoh"), now use substring to take the first half to get the desired answer.

    Saturday, June 8, 2013 3:24 AM