C# program to reverse a given string without using the predefined method

Here, we are going to learn how to reverse a given string without using the predefined method in C#?
Submitted by Nidhi, on October 12, 2020

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

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.