Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Reverse each word in a string using c#

Suggested Videos:
Part 10 - What happens if finally block thows an exception
Part 11 - What is the difference between is and as keyword in c#
Part 12 - Difference between int and Int32 in c#



In this video we will discuss how to reverse each word in a string using c#. This is a common c# interview question.



Reverse the following string
one two three four five

Output should be
eno owt eerht ruof evif

Here is the C# code that can do this
string inputString = "one two three four five";
string resultString = string.Join(" ", inputString
    .Split(' ')
    .Select(x => new String(x.Reverse().ToArray())));
Console.WriteLine(resultString);

Make sure you have the following using declarations
using System;
using System.Linq;

Here is what is happening with the above code
  • Split the input string using a single space as the separator. Split() method returns a string array that contains each word of the input string.
  • Select method, constructs a new string array, by reversing each character in each word.
  • Join method converts the string array into a string.

3 comments:

  1. Sir, I face interview .interviewer ask a que... i unable to answer
    Que is we have 5 methods m1 m2 m3 m4 m5 , and m1 call m2 ,m2 calls m3 like that upto m4 call m5 ,but when exception occure in m5 we must catch in m4 ,when exception occure in m4 we must catch in m3 like that how to do like that Please anwer it .using video

    ReplyDelete
  2. m1()
    {
    try
    {
    m2();
    }
    catch(exception ex)
    {
    }
    }
    m2()
    {
    try
    {
    m3();
    }
    catch(exception ex)
    {
    }
    }
    m3()
    {
    try
    {
    m4();
    }
    catch(exception ex)
    {
    }
    }
    m4()
    {
    try
    {
    m5();
    }
    catch(exception ex)
    {
    }
    }

    ReplyDelete
  3. Mr. Venkat, thank you for the amazing series on the C#.

    ReplyDelete

It would be great if you can help share these free resources