Reverse Each Word in a String in C#

Reverse Each Word in a String in C#

To achieve the output where each word is reversed in a string, you can split the input string into words, reverse each word, and then join them back together. Here's the C# code for that:

using System;

 

class Program

{

    static void Main()

    {

        string input = "one two three four";

       

        // Split the string into words

        string[] words = input.Split(' ');

 

        // Reverse each word and join them back together

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

        {

            char[] wordArray = words[i].ToCharArray();

            Array.Reverse(wordArray);

            words[i] = new string(wordArray);

        }

 

        // Join the reversed words with spaces and output the result

        string output = string.Join(" ", words);

        Console.WriteLine(output);

    }

}

Explanation:

  1. input.Split(' '): Splits the input string into an array of words.
  2. For each word in the array:
    • ToCharArray() converts the word into an array of characters.
    • Array.Reverse() reverses the characters in the array.
    • new string(wordArray) converts the reversed array of characters back to a string.
  3. Finally, string.Join(" ", words) joins the reversed words back into a single string with spaces in between.

Output:

eno owt eerht ruof





Reverse Each Word in a String in C# Using LINQ:


using System;

using System.Linq;


class Program

{

    static void Main()

    {

        string input = "one two three four";


        // Split the string into words, reverse each word, and join them back with a space

        string output = string.Join(" ", input.Split(' ').Select(word => new string(word.Reverse().ToArray())));


        Console.WriteLine(output);

    }

}


Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced