• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Saturday, August 15, 2020

Reverse Each Word in a Given String in C#

 Admin     August 15, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss How to Reverse Each Word in a Given String in C# with some examples. Please read our previous article where we discussed How to Reverse a String in C# program with some examples. As part of this article, we are going to use the following three approaches to reverse each word in a given string C#.
  1. Without using a built-in function
  2. Using Stack
  3. Using LINQ
Program Description:
The user will input a string and we need to reverse each word individually without changing its position in the string. Here, we will take the input as a string from the user, and then we need to reverse each word individually without changing their position in the sentence as shown in the below image.
How to Reverse Each Word in a Given String in C#

Method1: Without using any built-in function:
In the following example, we generate all words separated by space. Then reverse the words one by one.
using System;
using System.Collections.Generic;
using System.Text;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string originalString = Console.ReadLine();
            StringBuilder reverseWordString = new StringBuilder();
            List<char> charlist = new List<char>();
            for (int i = 0; i < originalString.Length; i++)
            {
                if (originalString[i] == ' ' || i == originalString.Length - 1)
                {
                    if (i == originalString.Length - 1)
                        charlist.Add(originalString[i]);
                    for (int j = charlist.Count - 1; j >= 0; j--)
                        reverseWordString.Append(charlist[j]);
                    reverseWordString.Append(' ');
                    charlist = new List<char>();
                }
                else
                {
                    charlist.Add(originalString[i]);
                }    
            }
            Console.WriteLine($"Reverse Word String : {reverseWordString.ToString()}");
            Console.ReadKey();
        }      
    }
}
Output:
Reverse Each Word in a Given String in C# without using built-in method

Method2: Using Stack to Reverse Each Word in C#
Here, we are using a stack to push all words before space. Then as soon as we encounter a space, we empty the stack. The program is self-explained, so please go through the comments line.
using System;
using System.Collections.Generic;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string originalString = Console.ReadLine();
            Stack<char> charStack = new Stack<char>();
            // Traverse the given string and push all characters
            // to stack until we see a space.  
            for (int i = 0; i < originalString.Length; ++i)
            {
                if (originalString[i] != ' ')
                {
                    charStack.Push(originalString[i]);
                }
                // When seeing a space, then print contents of the stack.  
                else
                {
                    while (charStack.Count > 0)
                    {
                        Console.Write(charStack.Pop());
                    }
                    Console.Write(" ");
                }
            }
            // Since there may not be space after last word.  
            while (charStack.Count > 0)
            {
                Console.Write(charStack.Pop());
            }
            
            Console.ReadKey();
        }      
    }
}
Method3: Using Linq to Reverse Each Word in C#
using System;
using System.Linq;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string originalString = Console.ReadLine();
            
            string reverseWordString = string.Join(" ", originalString
            .Split(' ')
            .Select(x => new String(x.Reverse().ToArray())));
            Console.WriteLine($"Reverse Word String : {reverseWordString}");
            Console.ReadKey();
        }      
    }
}
Output:
Reverse Each Word in a Given String in C# without using Linq

Code Explanation:
Split the input string using a single space as the separator.

The Split method is used for returning a string array that contains each word of the input string. We use the Select method for constructing a new string array, by reversing each character in each word. Finally, we use the Join method for converting the string array into a string.

In the next article, I am going to discuss How to Remove Duplicate Characters from a given string in C# using different mechanisms. I hope now you understood How to Reverse Each Word in a Given String in C# with different mechanisms.

Summary:
I hope this post will be helpful to write a program to Reverse Each Word in a Given String in C#
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape