- Try Code Live
-
Reverse the Substring of a String
-
Write a program to Reverse a Substring in the given string
Explanation:using System; public class ReverseSubString { public static void Main(string[] args) { var input = "My name is John"; string[] words = input.Split(' '); for(int i = 0; i < words.Length; i++) { var a = words[i].ToCharArray(); Array.Reverse(a); words[i] = new string(a); } string result = string.Join(" ", words); Console.WriteLine(result); } }- Split(' ') breaks the string into words.
- ToCharArray() converts each word to a character array.
- Array.Reverse() reverses the characters in place.
- string.Join(" ", words) joins them back with spaces.
Now lets see the concise LINQ version of the same solution:
using System; using System.Linq; class Program { static void Main() { string input = "My name is John"; string result = string.Join(" ", input.Split(' ') .Select(word => new string(word.Reverse().ToArray()))); Console.WriteLine(result); } }Output:
Explanation:yM eman si nhoJ- input.Split(' ') → splits the string into words.
- .Select(word => new string(word.Reverse().ToArray())) → reverses each word.
- string.Join(" ", ...) → joins the reversed words back into a single string.