Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Reverse of a string without using the Reverse function in C# and VB

4.00/5 (1 vote)
25 Jul 2011CPOL 7.7K  
/// /// Reverses an array (Change the type or use SetItem)/// /// The bytes/// The index in the bytes/// The length of bytes to reverseinternal static void Reverse(char[] array, int...
C#
/// <summary>
/// Reverses an array (Change the type or use SetItem)
/// </summary>
/// <param name="array">The bytes</param>
/// <param name="index">The index in the bytes</param>
/// <param name="len">The length of bytes to reverse</param>
internal static void Reverse(char[] array, int index, int len)
{
    char temp;//Comment out when using XOR Swap
    //O(n/2+1)
    //Length = 5 => {0,4}, {1,3}, ? {2,2} never hit because !(near < far)
    for (int near = index, far = len - 1; near < far; ++near, --far)
    {
        temp = array[near]; //          array[near] ^= array[far];
        array[near] = array[far];//          array[far] ^= array[near];
        array[far] = temp;//          array[near] ^= array[far];
    }
}
internal static void Reverse(char[] array)
{
   Reverse(array, 0, array.Length);
}
internal static String Reverse(String theString)
{
   char[] array = theString.ToCharArray();
   Reverse(array, 0, array.Length);
   return new String(array);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)