How to Reverse Each Word in a String Using C#

This is very common and frequently asked CSharp (C#) interview question.

String to be reversed:

DS tech blog

Output or the reversed string:

SD hcet golb

Our Logic in CSharp (C#):

  1. string input = "DS tech blog";  
  2.   
  3. string result = string.Join(" ", input  
  4.   
  5. .Split(' ')  
  6.   
  7. .Select(x => new String(x.Reverse().ToArray())));  
  8.   
  9. Console.WriteLine(result);   

Remember to include the below using statements:

  1. using System;  
  2.   
  3. using System.Linq;  
Explanation for the above code:
 
Split the input string using a single space as the separator.
  • Split() method for returning a string array that contains each word of the input string.

  • Select method for constructing a new string array, by reversing each character in each word.

  • Join method for converting the string array into a string.

References:

You can read about all these methods in detail on MSDN. Below are the links for your reference.

What do you think?

Dear Reader,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Learning.