C# Program to Reverse a String without using Reverse() Method
Last Updated :
16 Nov, 2021
C# has a built-in function to reverse a string. First, the string is converted to a character array by using ToCharArray() then by using the Reverse() the character array will be reversed, But in this article, we will understand how to Reverse a String without using Reverse().
Example
Input : Geek
Output : keeG
Input : For
Output : roF
Method 1: Using a for loop to reverse a string.
An empty string is declared and name as ReversedString. The input string will be iterated from right to left and each character is appended to the ReversedString. By the end of the iteration, the ReversedString will have the reversed string stored in it.
C#
using System;
class GFG{
public static string Reverse( string Input)
{
char [] charArray = Input.ToCharArray();
string reversedString = String.Empty;
for ( int i = charArray.Length - 1; i > -1; i--)
{
reversedString += charArray[i];
}
return reversedString;
}
static void Main( string [] args)
{
Console.WriteLine(Reverse( "GeeksForGeeks" ));
}
}
|
Method 2: Using a while loop to reverse a string.
In this method, an empty string is declared and name as reversedString now the input string will be iterated from right to left using the while loop, and each character is appended to the reversedString. By the end of the iteration, the reversedString will have the reversed string stored in it.
C#
using System;
class GFG{
public static string Reverse( string Input)
{
char [] charArray = Input.ToCharArray();
string reversedString = String.Empty;
int length, index;
length = charArray.Length - 1;
index = length;
while (index > -1)
{
reversedString = reversedString + charArray[index];
index--;
}
return reversedString;
}
static void Main( string [] args)
{
Console.WriteLine(Reverse( "GeeksForGeeks" ));
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...