How To Reverse String Write Without Change Word Position In C#

Today in this article, I will explain how we can reverse the string write without the change of word position. So let’s start.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReverseStringWithoutChangeOfWordPosition
    class Program
        static void Main(string[] args)
            string str = "Hello World";
            string revstr = "";
            foreach (var word in str.Split(' '))
                string temp = "";
                foreach (var c in word.ToCharArray())
                    temp = c + temp;
                revstr = revstr + temp + " ";

The above C# code reverses the order of letters in each word of a given string while keeping the words in their original position. In the above code, The `for each` loop is used to iterate through each word in the string by splitting the string with a space delimiter using the `Split` method. For each word, an empty string variable `temp` is initialized to store the reversed word. Another `foreach` loop is used to iterate through each character in the word using the `ToCharArray` method. For each character, it is appended to the start of the `temp` string variable. This reverses the order of the characters in the word. After all the characters in the word have been processed, the reversed word `temp` is appended to the end of the `revstr` string variable, followed by a space character. The `foreach` loop continues until all the words in the string have been processed. Finally, the reversed string `revstr` is output to the console.


Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories