Home
C#
Reverse Words
Updated Apr 4, 2023
Dot Net Perls
Reverse words. Words in a C# string can be reversed. We combine several methods and concepts from .NET, resulting in a straightforward method.
C# method info. Consider the Split and Join methods. We can use one to separate words, and the other to merge them back together.
String Reverse
Example code. To begin, we see the sentences we want to reverse. We use the const modifier here, which means the strings can't be changed.
static
const
Info ReverseWords() is static because it does not save state. It separates words on spaces with Split.
String Split
Then ReverseWords reverses the words with the efficient Array.Reverse method. It then joins the array on a space.
Array.Reverse
string.Join
Next The Console.WriteLine static method prints the sentence results to the console.
Console.WriteLine
using System;

static class WordTools
{
    /// <summary>
    /// Receive string of words and return them in the reversed order.
    /// </summary>
    public static string ReverseWords(string sentence)
    {
        string[] words = sentence.Split(' ');
        Array.Reverse(words);
        return string.Join(" ", words);
    }
}

class Program
{
    static void Main()
    {
        const string s1 = "blue red green";
        const string s2 = "c# rust python";

        string rev1 = WordTools.ReverseWords(s1);
        Console.WriteLine(rev1);

        string rev2 = WordTools.ReverseWords(s2);
        Console.WriteLine(rev2);
    }
}
green red blue python rust c#
Solution notes. Many teams prefer simple and straightforward solutions to this sort of problem. Simple methods are easy to maintain, but may have poor performance.
And Elaborate and clever methods, with clever syntax or optimizations, often just lead to more bugs.
A summary. We reversed words in a string using a method that is clear and uses few lines of code. It is easy to enhance when your requirements change.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 4, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen