Share Blog

Tuesday, April 05, 2016

How to Reverse Each Word in a String Using C#

Example :Sunil Kumar

Reverse String :linuS ramuK

Write a Code


static void Main(string[] args)
        {
            string str = "Sunil Kumar";
            var reversedWords = string.Join(" ",
      str.Split(' ')
         .Select(x => new String(x.Reverse().ToArray()))
         .ToArray());
            Console.WriteLine(reversedWords);
            Console.ReadLine();


        }

Result 




In other words:
·         Split on spaces
·         For each word, create a new word by treating the input as a sequence of characters, reverse that sequence, turn the result into an array, and then call the string(char[]) constructor
·         Depending on framework version, call ToArray() on the string sequence, as .NET 4 has more overloads available
·         Call string.Join on the result to put the reversed words back together again.