Reverse the ordering of words in a String

To reverse the ordering of words in a string, you can split the string into individual words, reverse the order of the words, and then join them back into a new string. Here’s an example implementation in C#:

using System;

public class StringReverser
{
    public static string ReverseWords(string sentence)
    {
        // Split the sentence into individual words
        string[] words = sentence.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

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

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

        return reversedSentence;
    }
}

Here’s how you can use the ReverseWords method:

string sentence = "Hello world, how are you?";

string reversedSentence = StringReverser.ReverseWords(sentence);
Console.WriteLine(reversedSentence);

The output will be: “you? are how world, Hello”

In this implementation:

  1. The ReverseWords method takes a sentence parameter, which is the string whose word ordering needs to be reversed.
  2. The sentence string is split into individual words using the Split method, using space as the delimiter. The StringSplitOptions.RemoveEmptyEntries option is used to remove any empty entries.
  3. The order of the words is reversed using the Array.Reverse method.
  4. The reversed words are joined back into a string using the string.Join method, with a space as the separator.
  5. The reversed sentence is returned as the result.

By reversing the order of words in the string, you can achieve the desired outcome of reversing the ordering of words while preserving the words themselves.

error: Content is protected !!