Reverse a String using C#

Function to Reverse a String in C#:

The input parameter for the ReverseString function is a string.
The ToCharArray function is first used to turn the input string into an array of characters.
Then using a reverse FOR LOOP, the items inside the Character Array are traversed and on by one each character is appended to another string i.e. output.
Thus by appending the character one by one in reverse order, a reverse string is generated.
Finally, the output string is returned.

C#:

private static string ReverseString(string input)
{
    string output = string.Empty;
    char[] chars = input.ToCharArray();
    for (int i = chars.Length - 1; i >= 0; i--)
    {
        output += chars[i];
    }
 
    return output;
}

Reverse a String in ASP.Ner with C#:

We will now demonstrate how to reverse a string in ASP.Net using C# and VB.Net by using the aforementioned ReverseString method.
CSS Markup
Three elements of the HTML markup are an ASP.Net TextBox, a Button, and a Label. An OnClick event handler that performs string reversal has been given to the button.
<asp:TextBox ID="txtName" runat="server" />
<asp:Button ID="btnReverse" Text="Reverse" runat="server" OnClick="Reverse" />
<hr />
<asp:Label id="lblReverseString" runat="server" />

Code:

The TextBox’s value is provided to the ReverseString function (described above) when the Reverse Button is clicked, and the reversed string that is returned is assigned to the Label control.

C#:

protected void Reverse(object sender, EventArgs e)
{
    lblReverseString.Text = ReverseString(txtName.Text);
}

Submit a Comment

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

Subscribe

Select Categories