Friday, November 13, 2009

C# Reverse a string

If somebody ask you to write a simple method that reverse an input string, here is the code.

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string result = ReverseString("i am fine");
}
public static string ReverseString(string input)
{
char[] output = input.ToCharArray();
char[] result = new char [output.Length ];
int j = 0;
for (int i = output.Length - 1 ; i > 0; i--)
{
result[j] = (char)output[i];
j++;
}
return new string(result);
}
}
}
,
Another simple way

public static string Reverse( string s ){ char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); return new string( charArray );}

No comments: