How to Reverse the Order Of Words In A String

In this blog, I am going to explain the program to reverse the order of words in a string using a static/extension method.

Introduction
 
In this blog, I am going to explain the program to reverse the order of words in a string.
 
Software Requirements
  • C# 3.0 or higher,
  • Visual Studio or Notepad

Example

Original Text: Singh Sanjit
 
Reversed order of words: Sanjit Singh
 
Program
  1. using System;  
  2. namespace WordReverse {  
  3.  public static class Extension {  
  4.   // This method will be treated as an extension and Static based on the way of call  
  5.   public static string[] ReverseWord(this string[] strArray) {  
  6.    if (strArray is null) {  
  7.     throw new ArgumentNullException(nameof(strArray));  
  8.    }  
  9.    string temp;  
  10.    int j = strArray.Length - 1;  
  11.    for (int i = 0; i < j; i++) {  
  12.     temp = strArray[i];  
  13.     strArray[i] = strArray[j];  
  14.     strArray[j] = temp;  
  15.     j--;  
  16.    }  
  17.    return strArray;  
  18.   }  
  19.  }  
  20.  class Program {  
  21.   static void Main() {  
  22.    Console.WriteLine("(Input is Optional and Default value will be 'Community of Software and Data Developers'");  
  23.    Console.WriteLine("Enter your data to Reverse otherwise just Hit Enter");  
  24.    var sampleText = Console.ReadLine();  
  25.    if (string.IsNullOrEmpty(sampleText))  
  26.     sampleText = "Community of Software and Data Developers";  
  27.    Console.WriteLine("=======================================================");  
  28.    Console.WriteLine($ "Original Text : {sampleText}");  
  29.    Console.WriteLine("=======================================================");  
  30.    Console.Write($ "Reversed order of words (Static Method): ");  
  31.    DisplayArrayValues(Extension.ReverseWord(sampleText.Split(' ')));  
  32.    Console.WriteLine("======================================================");  
  33.    Console.Write($ "Reversed order of words (Extension Method): ");  
  34.    DisplayArrayValues(sampleText.Split(' ').ReverseWord());  
  35.    Console.ReadLine();  
  36.   }  
  37.   static void DisplayArrayValues(string[] strArray) {  
  38.    if (strArray is null) {  
  39.     throw new ArgumentNullException(nameof(strArray));  
  40.    }  
  41.    for (int i = 0; i < strArray.Length; i++)  
  42.     Console.Write(strArray[i] + " ");  
  43.    Console.WriteLine();  
  44.   }  
  45.  }  

Now run the code.
 
If the User does not enter anything, then the default value will be "https://www.c-sharpcorner.com." The following example is without input.
 
 
 
If User enters "power is Knowledge" it should look like the following:
 
 
 
Thank you so much for reading my blog.