How to reverse the middle words of a string in C#

1 Answer

0 votes
using System;
using System.Linq;

class Program
{
    static string ReverseMiddleWords(string input) {
        var words = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);

        if (words.Length < 3)
            return input; // nothing to reverse

        for (int i = 1; i < words.Length - 1; i++) {
            words[i] = new string(words[i].Reverse().ToArray());
        }

        return string.Join(" ", words);
    }

    static void Main()
    {
        string s = "Hello how are you today";
        
        Console.WriteLine(ReverseMiddleWords(s));
    }
}



/*
run:

Hello woh era uoy today

*/

 



answered Dec 12, 2019 by avibootz
edited Dec 25, 2025 by avibootz
...