Monday, February 20, 2012

Reverse String in C# and .Net

Example program that reverses strings [C#]

using System;
static class StringHelper
{
///
/// Receives string and returns the string with its letters reversed.
///

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

class Program
{
static void Main()
{
Console.WriteLine(StringHelper.ReverseString("framework"));
Console.WriteLine(StringHelper.ReverseString("samuel"));
Console.WriteLine(StringHelper.ReverseString("example string"));
}
}

Output

krowemarf
leumas
gnirts elpmaxe

-------------------------------------------------------------------------------------

on .net

Dim strOrgText As String
Dim strRevText As [Char]()
Dim array As Array

strOrgText = Me.txtTheString.Text
strRevText = strOrgText.ToCharArray
array.Reverse(strRevText)
Me.lblResult.Text = strRevText

----------------------------------------------------------------------------------

on .net

Program that reverses strings [VB.NET]

Module Module1
Sub Main()
' Test.
Console.WriteLine(Reverse("perls"))
Console.WriteLine(Reverse("sam"))
Console.WriteLine(Reverse(Reverse("perls")))
End Sub

'''
''' Reverse input string.
'''

Function Reverse(ByVal value As String) As String
' Convert to char array.
Dim arr() As Char = value.ToCharArray()
' Use Array.Reverse function.
Array.Reverse(arr)
' Construct new string.
Return New String(arr)
End Function
End Module

Output

slrep
mas
perls

0 comments:

 
Header Image by Colorpiano Illustration