Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

Reverse Each Word in a Given String in C#

 

Reverse Each Word in a Given String in C#

in this article we will see how to write programme for reverse each word in a string

Without using any built-in function

public static void ReverseEachWord()

        {

            Console.Write("Enter a String : ");

            string inputString = Console.ReadLine();

            StringBuilder reverseWordString = new StringBuilder();

            List<char> charlist = new List<char>();

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

            {

                if (inputString[i] == ' ' || i == inputString.Length - 1)

                {

                    if (i == inputString.Length - 1)

                        charlist.Add(inputString[i]);

                    for (int j = charlist.Count - 1; j >= 0; j--)

                        reverseWordString.Append(charlist[j]);

                    reverseWordString.Append(' ');

                    charlist = new List<char>();

                }

                else

                {

                    charlist.Add(inputString[i]);

                }

            }

            Console.WriteLine($"Reverse Word String : {reverseWordString.ToString()}");

        }


output




Using Linq to Reverse Each Word in C#

public static void ReverseEachWord()

        {

            Console.Write("Enter a String : ");

            string inputString = Console.ReadLine();

 

            string reverseWordString = string.Join(" ", inputString

            .Split(' ')

            .Select(x => new String(x.Reverse().ToArray())));

            Console.WriteLine($"Reverse Word String : {reverseWordString}");

        }


output



Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now