locked
Reversing a string without using temporary string variables RRS feed

  • Question

  • Hi

        I want to reverse  a string like "Hi I am Fayaz" to "Fayaz am I Hi" but dont use the temporary string variables.

    Tuesday, September 4, 2012 1:13 PM

Answers

  • string a = "Hello World":
    
    a = string.Join(" ", a.Split().Reverse().ToArray());



    Regards,
    Bubu
    http://zsvipullo.blogspot.it

    Please mark my answer if it helped you, I would greatly appreciate it.


    • Edited by Sergio Russo Tuesday, September 4, 2012 1:23 PM
    • Marked as answer by Sk Fayaz Alam Tuesday, September 4, 2012 1:29 PM
    • Unmarked as answer by Sk Fayaz Alam Friday, November 2, 2012 5:21 AM
    • Marked as answer by Sk Fayaz Alam Friday, November 2, 2012 5:21 AM
    Tuesday, September 4, 2012 1:22 PM

All replies

  • Do as:

                string str = "Hi I am Fayaz";
                string[] arr = str.Split(' ');
                Array.Reverse(arr);
                str = String.Join(" ", arr.Select(p => p.ToString()).ToArray());


    Mitja

    Tuesday, September 4, 2012 1:16 PM
  • string a = "Hello World":
    
    a = string.Join(" ", a.Split().Reverse().ToArray());



    Regards,
    Bubu
    http://zsvipullo.blogspot.it

    Please mark my answer if it helped you, I would greatly appreciate it.


    • Edited by Sergio Russo Tuesday, September 4, 2012 1:23 PM
    • Marked as answer by Sk Fayaz Alam Tuesday, September 4, 2012 1:29 PM
    • Unmarked as answer by Sk Fayaz Alam Friday, November 2, 2012 5:21 AM
    • Marked as answer by Sk Fayaz Alam Friday, November 2, 2012 5:21 AM
    Tuesday, September 4, 2012 1:22 PM
  • Or even shorter:

     string str = "Hi I am Fayaz";
     str = String.Join(" ", str.Split(' ').Reverse().Select(s => s.ToString()).ToArray());


    Mitja

    Tuesday, September 4, 2012 1:26 PM
  • Thank u very much Russo.Its Really helping me.
    Tuesday, September 4, 2012 1:29 PM
  •             var input = "This is you";
                var array = input.ToArray();
                for (int i = 0, j = array.Length-1; i < j; i++, j--)
                {
                    array[i] ^= array[j];
                    array[j] ^= array[i];
                    array[i] ^= array[j];
                }
                Console.WriteLine(array);
                Console.Read();
    How it is different from others ? This support old versions of .net framework or where LINQ is not available.

    If this post answers your question, please click Mark As Answer. If this post is helpful please click Mark as Helpful.

    Regards,
    Nair S


    • Edited by Nair S Tuesday, September 4, 2012 2:12 PM sl
    Tuesday, September 4, 2012 2:07 PM