none
Reverse the string using c# RRS feed

  • Question

  • Hi ,

    I am new in c# and i would like to revers the string as below format

    Scenario 1:

    Direct: 123ABC456

    Revers : 56C4AB2301

    Scenario 2:

    Direct : 123ABC45

    Reverse: 45BC3A12

    Pleas help me to get this.


    Regards Venkat


    Tuesday, October 22, 2019 2:23 AM

Answers

  • If you prefer LINQ, then check this example:

    string direct = "123ABC456";

     

    string reverse =

                  string.Join( null,

                         direct

                               .Reverse( )

                               .Concat( Enumerable.Repeat( '0', direct.Length % 2 ) )

                               .Select( ( c, i ) => new { c, i } )

                               .GroupBy( g => g.i / 2, g => g.c )

                               .Select( a => string.Concat( a.Reverse( ) ) )

                         );

     

    Console.WriteLine( direct );

    Console.WriteLine( reverse );

     


    • Edited by Viorel_MVP Tuesday, October 22, 2019 5:46 AM
    • Marked as answer by VENKAT YADAV Tuesday, October 22, 2019 7:02 AM
    Tuesday, October 22, 2019 5:41 AM

All replies

  • Hi,

    I'm afraid your sample string is wrong.
    I guess, in Scenario 1, Direct would be "0123ABC456". 

    The number of letters in Direct should be Even, instead of Odd number.
    Is this correct?

    Regards,

    Ashidacchi -- http://hokusosha.com

    Tuesday, October 22, 2019 3:43 AM
  • Hi Ashidacchi,

    sometime i will get even and some time Odd count.


    Regards Venkat

    Tuesday, October 22, 2019 5:20 AM
  • hi,

    i should be pare with two digits always so if i left with one digit then should be add '0' in front of it.


    Regards Venkat

    Tuesday, October 22, 2019 5:21 AM
  • If you prefer LINQ, then check this example:

    string direct = "123ABC456";

     

    string reverse =

                  string.Join( null,

                         direct

                               .Reverse( )

                               .Concat( Enumerable.Repeat( '0', direct.Length % 2 ) )

                               .Select( ( c, i ) => new { c, i } )

                               .GroupBy( g => g.i / 2, g => g.c )

                               .Select( a => string.Concat( a.Reverse( ) ) )

                         );

     

    Console.WriteLine( direct );

    Console.WriteLine( reverse );

     


    • Edited by Viorel_MVP Tuesday, October 22, 2019 5:46 AM
    • Marked as answer by VENKAT YADAV Tuesday, October 22, 2019 7:02 AM
    Tuesday, October 22, 2019 5:41 AM
  • thanks its working..

    Regards Venkat

    Tuesday, October 22, 2019 7:02 AM