2
Reply

How to reverse string in C#

Kirtesh Shah

Kirtesh Shah

1y
621
0
Reply

How to reverse string in C#

    //For high-performance

    string input = "Hello World";

    Span<char> buffer = stackalloc char[input.Length];

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

    {

    buffer[i] = input[input.Length - 1 - i];

    }

    string reversed = new string(buffer);

    Console.WriteLine(reversed);

    Method 1: Using ToCharArray() and Array.Reverse()

    string str = “hello”;
    char[] charArray = str.ToCharArray();
    Array.Reverse(charArray);
    string reversed = new string(charArray);
    Console.WriteLine(reversed); // Output: “olleh”

    Method 2: Using LINQ
    using System;
    using System.Linq;

    string str = “world”;
    string reversed = new string(str.Reverse().ToArray());
    Console.WriteLine(reversed); // Output: “dlrow”