Write A C# Program To Reverse The Words Of A Sentence

Do you want to know how to reverse the words of a sentence in C#? In this C# tutorial, I will explain how to write a C# program to reverse the words of a sentence.

To reverse the words of a sentence in C#, you can split the sentence into words using string.Split(), reverse the array of words using Array.Reverse(), and then join the words back into a sentence using string.Join(). This method is effective for manipulating the order of words while maintaining their original form.

Write a C# Program to Reverse the Words of a Sentence

Now, let us see step by step how to write a C# program to reverse the words of a sentence.

To do this demo, I will use a C# console application using Visual Studio.

First, we need to accept a sentence from the user. We can do this using Console.ReadLine().

Console.WriteLine("Enter a sentence:");
string sentence = Console.ReadLine();

Next, we split the sentence into an array of words. This is done using the String.Split() method, which splits a string into an array of substrings based on the specified delimiters. In our case, the delimiter is a space.

string[] words = sentence.Split(' ');

Now, we need to reverse the order of the words in the array. This can be achieved using the Array.Reverse() method.

After reversing the words, we need to join them back into a single string. We use String.Join() method for this, specifying a space as the separator.

string reversedSentence = String.Join(" ", words);

Finally, we display the reversed sentence to the user.

Console.WriteLine("Reversed Sentence: " + reversedSentence);

Here’s the complete C# code to reverse the words of a sentence:

using System;

class Program
{
    static void Main()
    {
        // Prompt the user to enter a sentence
        Console.WriteLine("Enter a sentence:");
        string sentence = Console.ReadLine();

        // Split the sentence into words
        string[] words = sentence.Split(' ');

        // Reverse the order of the words
        Array.Reverse(words);

        // Join the reversed words back into a sentence
        string reversedSentence = String.Join(" ", words);

        // Output the reversed sentence
        Console.WriteLine("Reversed Sentence: " + reversedSentence);

        // Keep the console window open
        Console.WriteLine("\nPress any key to exit.");
        Console.ReadKey();
    }
}

Once you run the code, this code will take a sentence input from the user, reverse the order of the words, and then output the reversed sentence. Check out the screenshot below:

write a c# program to reverse the words of a sentence

Conclusion

I hope you learn how to write a c# program to reverse the words of a sentence. We executed the program using the Visual Studio console application.

You may also like: