C# - Reverse a String Without Using Predefined Method

Given a string, we have to reverse a string without using predefined method using C# program.
Submitted by Nidhi, on October 12, 2020 [Last updated : March 21, 2023]

Here, we will read a string and then reverse the string without using any predefined method.

C# program to reverse a string without using predefined method

The source code to reverse a given string without using the predefined method is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# Program to reverse a given string without 
//using the predefined method.

using System;

class Demo
{
    static string StrReverse(string str)
    {
        string reverse = "";
        int strLen=0;

        strLen = str.Length - 1;
        while (strLen >= 0)
        {
            reverse = reverse + str[strLen];
            strLen--;
        }
        return reverse;

    }
    static void Main(string[] args)
    {
        string str      = "";
        string reverse  = "";

        Console.Write("Enter a string: ");
        str = Console.ReadLine();

        reverse = StrReverse(str);

        Console.WriteLine("Reverse of string is: "+ reverse);
    }
}

Output

Enter a string: IncludeHelp
Reverse of string is: pleHedulcnI
Press any key to continue . . .

Explanation

Here, we created two static methods StrReverse() and Main(). The StrReverse() method is used to reverse a specified string, here we find the length of the string then access character from last to the start of the string and append each character to another string "reverse". At the end string "reverse" contains the reverse value of the given string that will be returned to the calling method.

Now look to the Main() method, In the Main() method, we read the value of the string and passed to the StrReverse() method that returned the reverse of the string and then finally prints the result on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.