C# Program to reverse words in a String -Learn how to reverse words of a given input sentence using mathematical approach, string handling functions with examples.
Input-1
Good practice give good coding skills
Output-1
dooG ecitcarp evig doog gnidoc slliks
Input-2
This is very interesting Program
Output-2
sihT si yrev gnitseretni margorP
Example C# Program to reverse words in a String using mathematical approach
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter the Input String");
string s = Console.ReadLine();
List lst = new List();
StringBuilder str = new StringBuilder();
for (int i = 0; i < s.Length; i++) { if (s[i] == ' ' || i == s.Length - 1) { if (i == s.Length - 1) { lst.Add(s[i]); } for (int k = lst.Count - 1; k >= 0; k--)
{
str.Append(lst[k]);
}
lst = new List();
str.Append(" ");
}
lst.Add(s[i]);
}
Console.WriteLine(str);
}
}
Example C# Program to reverse words in a String using string handling functions
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter the Input String");
string s = Console.ReadLine();
char[] letters = s.ToCharArray();
Array.Reverse(letters);
StringBuilder str = new StringBuilder();
str.Append(letters);
string[] s1 = str.ToString().Split(' ');
for (int i = s1.Length - 1; i >= 0; i--)
{
Console.Write(s1[i]+" ");
}
}
}
Input
Please Enter the Input String
dooG ecitcarp evig doog gnidoc slliks
Output
Good practice give good coding skills