Tech Point Fundamentals

Monday, November 22, 2021

C# Program to Reverse Each Word of a String

C# Program to Reverse Each Word of a String

coding-interview-question-csharp

Most of the IT companies check the coding skills and problem-solving skills as well along with the theoretical interview questions. Sometimes you are free to write the pseudo code and sometimes you are asked to write the complete program either on any paper or any editor. 


This question is asked in the coding interview to write the program. Here you can find the program as well as a live running program so that you can test the program immediately.


Watch our videos here





Question: 


How can you reverse each word in a given sentence? Write a program to reverse each word of a given sentence.



C# Program To Reverse Each Word of a String


       
 

// Author 	: Tech Point Fundamentals
// Website 	: www.techpointfunda.com
// Channel	: https://www.youtube.com/c/TechPointFundamentals
// Demo		: Reverse each word of the sentence

using System;
using System.Text;
using System.Collections.Generic;

public class Program
{
public static void Main()
{
	string inputString = "Tech Point Fundamentals";
	string reversedString = ReverseWord(inputString);
	
	Console.WriteLine("Input String : " + inputString);
	Console.WriteLine("Reversed Word : " + reversedString);
}
	
	
static string ReverseWord(string inputString)  
{        
	StringBuilder reversedWord = 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--)  
				 reversedWord.Append(charList[j]);  

			 reversedWord.Append(' ');  
			 charList = new List<char>();  
		 }  
		 else  
			 charList.Add(inputString[i]);  
	 }  
	
	return reversedWord.ToString();		
}
}





Output: 

Input String : Tech Point Fundamentals
Reversed Word : hceT tnioP slatnemadnuF


Live Demo






No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.