Reverse Words in a String

Below code snippet shows 3 ways to reverse words in the string

  1. Approach 1 describes traditional ways of reversing entire string, then using space delimiter reverse each word.
  2. Approach 2 – Split string using space and reverse the array using .NET built method of Array.reverse
  3. Approach 3 – Similar to 2 but using only one line of code
    class Program
    {
        static void Main(string[] args)
        {
            string input = "Aamol Gote's blog is my tech net know hows";
            Approach1UsingCharArray(input);
            Approach2UsingArrayReverse(input);
            Approach3UsingSingleLOC(input);
            Console.ReadLine();
        }


        private static void Approach1UsingCharArray(string input)
        {
            string reversedStr = ReverseString(input);
            StringBuilder sb = new StringBuilder(reversedStr.Length);
            foreach (string str in reversedStr.Split(' '))
            {
                sb.Append(string.Concat(ReverseString(str), ' '));
            }
            Console.WriteLine(sb.ToString().Trim());
        }

        private static string ReverseString(string str)
        {
            char[] stringContent = str.ToCharArray();
            for (int start = 0, end = stringContent.Length - 1; start < end; start++, end--)
            {
                char temp = stringContent[start];
                stringContent[start] = stringContent[end];
                stringContent[end] = temp;
            }
            return new string(stringContent);
        }

        private static void Approach2UsingArrayReverse(string input)
        {
            string[] strArr = input.Split(' ');
            IEnumerable<string> strReverArr = strArr.Reverse<string>();
            StringBuilder sb = new StringBuilder(input.Length);
            foreach (string str in strReverArr)
            {
                sb.Append(string.Concat(str, ' '));
            }
            Console.WriteLine(sb.ToString().Trim());
        }

        private static void Approach3UsingSingleLOC(string input)
        {
            string reversed = string.Join(" ", input.Split(' ').ToArray<string>().Reverse<string>());
            Console.WriteLine(reversed);
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s