C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Main: We see the sentences we want to reverse. We use the const modifier here, which means the strings can't be changed.
constReverseWords: First this method is static because it doesn't save state. It separates words on spaces with Split.
SplitThen: ReverseWords reverses the words with the efficient Array.Reverse method. It then joins the array on a space.
Array.ReverseJoinNext: The Console.WriteLine static method prints the sentence results to the console.
ConsoleC# 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