C# Reverse Words

Reverse the words in a sentence with the Split, Join, and Array.Reverse methods.
Reverse words. Words in a string can be reversed. This might answer a common interview question. We combine several methods and concepts from the .NET runtime, resulting in a straightforward method.Reverse String
Example. First, the most clever and obscure method is often not preferred. My approach here was to develop a simple and reliable static method. Your team members will be glad to maintain this code.Static

Main: We see the sentences we want to reverse. We use the const modifier here, which means the strings can't be changed.


ReverseWords: First this method is static because it doesn't save state. It separates words on spaces with Split.


Then: ReverseWords reverses the words with the efficient Array.Reverse method. It then joins the array on a space.


Next: The Console.WriteLine static method prints the sentence results to the console.

C# program that reverses sentences 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 = "Bill Gates is the richest man on Earth"; const string s2 = "Srinivasa Ramanujan was a brilliant mathematician"; string rev1 = WordTools.ReverseWords(s1); Console.WriteLine(rev1); string rev2 = WordTools.ReverseWords(s2); Console.WriteLine(rev2); } } Output Earth on man richest the is Gates Bill mathematician brilliant a was Ramanujan Srinivasa
Notes, solutions. Many teams prefer simple and straightforward solutions to this sort of problem. They are easy to maintain. Elaborate and clever methods, with clever syntax or optimizations, often just lead to more bugs.
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. Other sites show more complex solutions or faster solutions.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to