Reverse each word in a string using c#

Reverse each word in a string using c#

Howdy Reader,

In this post we will discuss how to reverse each word in a string using c#.

This is very common & frequently asked CSharp (C#) interview question too. Click To Tweet

String to be reversed:

DS tech blog

Output or the reversed string:

SD hcet golb

Reverse each word in a string using c#?

Our Logic in CSharp (C#):

Remember to include the below using statements:

Screenshot:

Reverse each word in a string using c#

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.

Download code files for free 

Share a Tweet OR  Like us on Facebook OR Plus us on Google to download the code file.

Hope you have enjoyed this article. Please feel free to comment below.

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 Coding!

  • Saleem

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

  • Diego

    Saleem, your script is mirroring the input (“DS tech blog” => “golb hcet SD”), not reversing each word in a string (sentence?). You first need to identify the “words” (split by space) in the sentence.

    public static string ReverseString(string s)
    {
    return string.Join(” “,
    s.Split(‘ ‘).Select(arr => new String(arr.Reverse().ToArray())));
    }

  • Correctly said @Diego

  • Pingback: Difference between initialize and instantiate in C# - Dipendra Shekhawat()