Tuesday, August 23, 2011

C# code sample for reversing a string

Question: Write a method to reverse a string

Test case:
string s = "This is Test";
Output string s="tseT si sihT";

Possible solutions:
1. Use Array.Reverse
2. Use for loop and print reverse
3. Use stack
4. Use recursion

1. Use Array.Reverse
// Using Reverse
        public static string ReverseString(string s)
        {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }

2. For loop
//Using For Loop to reverse string
        public static string RevStrForLoop(string s)
        {
            int len = s.Length;
            char[] arr = new char[len];
            for (int i = 0; i < s.Length; i++)
            {
                arr[i] = s[len-i-1];
            }
            return new string(arr);
        }

3.Use Stack
 public static string UsingStack(string s)
        {
            Stack<string> stack = new Stack<string>();
            string rs = string.Empty;

            for (int i=0; i<s.Length ; i++)
            {
                stack.Push(s.Substring(i,1));
               
            }
            for (int i = 0; i < s.Length; i++)
            {
                rs += stack.Pop();

            }
            return rs;
        }




No comments:

Post a Comment