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.
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.