C# Reverse WordsReverse the words in a sentence with the Split, Join, and Array.Reverse methods.
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
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.const
ReverseWords: First this method is static because it doesn't save state. It separates words on spaces with Split.Split
Then: ReverseWords reverses the words with the efficient Array.Reverse method. It then joins the array on a space.Array.ReverseJoin
Next: The Console.WriteLine static method prints the sentence results to the console.Console
C# program that reverses sentences
static class WordTools
/// Receive string of words and return them in the reversed order.
public static string ReverseWords(string sentence)
string words = sentence.Split(' ');
return string.Join(" ", words);
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);
string rev2 = WordTools.ReverseWords(s2);
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.