1 / 4
2 / 4
3 / 4
4 / 4

Saturday, 2 September 2023

Reverse the words of a sentence in C# without using predefined Reverse Method

 In this scenario, we have to reverse each word of a sentence. For example, the input string is "Hello, This is Me", the output will be ",olleH sihT si eM".





Program

public class Program

{

    public static void Main(string[] args)

    {

string inputString="Hello World, This is a Reverse word Example";

string[] stringArr = inputString.Split(' ');

            string result= string.Empty;

            for (int i=0;i< stringArr.Length;i++)

            {

                char[] charArr= stringArr[i].ToCharArray();

                for (int j= charArr.Length- 1;j>=0;j--)

                {

                    result += charArr[j];

                }

                result +=" ";

            }

Console.WriteLine(result)

    }

}

O/P- ,olleH sihT si eM

Explanation

Taking the Input from the user/ Initlilising with any string value by hardcoding

string inputString="Hello World, This is a Reverse word Example";

or

Console.WriteLine("Enter a string");

string inputString=Console.ReadLine();


Split the input string when there is a space.

string[] stringArr = inputString.Split(' ');


Declaring a variable to store the result

string result= string.Empty;


Loop to read all split strings

for (int i=0;i< stringArr.Length;i++)

 {

        Converting the ith position string to a character array

   char[] charArr= stringArr[i].ToCharArray();

        Loop through the character array, but read it from the last index

   for (int j= charArr.Length- 1;j>=0;j--)

    {

            Store the reversed characters in the "result" variable by concatenating

      result += charArr[j];

    }

        Adding a space when the iteration of one split string is done

    result +=" ";

 }

Printing the result

Console.WriteLine(result);


Hope this will help you to understand the program.

Thank you


No comments:

Post a Comment

If you have any doubts please let me know