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
- using System;
- namespace WordReverse {
- public static class Extension {
-
- public static string[] ReverseWord(this string[] strArray) {
- if (strArray is null) {
- throw new ArgumentNullException(nameof(strArray));
- }
- string temp;
- int j = strArray.Length - 1;
- for (int i = 0; i < j; i++) {
- temp = strArray[i];
- strArray[i] = strArray[j];
- strArray[j] = temp;
- j--;
- }
- return strArray;
- }
- }
- class Program {
- static void Main() {
- Console.WriteLine("(Input is Optional and Default value will be 'Community of Software and Data Developers'");
- Console.WriteLine("Enter your data to Reverse otherwise just Hit Enter");
- var sampleText = Console.ReadLine();
- if (string.IsNullOrEmpty(sampleText))
- sampleText = "Community of Software and Data Developers";
- Console.WriteLine("=======================================================");
- Console.WriteLine($ "Original Text : {sampleText}");
- Console.WriteLine("=======================================================");
- Console.Write($ "Reversed order of words (Static Method): ");
- DisplayArrayValues(Extension.ReverseWord(sampleText.Split(' ')));
- Console.WriteLine("======================================================");
- Console.Write($ "Reversed order of words (Extension Method): ");
- DisplayArrayValues(sampleText.Split(' ').ReverseWord());
- Console.ReadLine();
- }
- static void DisplayArrayValues(string[] strArray) {
- if (strArray is null) {
- throw new ArgumentNullException(nameof(strArray));
- }
- for (int i = 0; i < strArray.Length; i++)
- Console.Write(strArray[i] + " ");
- Console.WriteLine();
- }
- }
- }
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.