Created
August 31, 2015 18:37
-
-
Save softwarespot/25fd77575a5992050fde to your computer and use it in GitHub Desktop.
Example of reversing a char array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace ScratchPad | |
{ | |
class Program | |
{ | |
public static void Main() | |
{ | |
// A char array that will be reversed | |
// You will also notice that it showcases how to store more than one variable in the loop that is local to the scope | |
char[] reverse = { 'R', 'e', 'v', 'e', 'r', 's', 'e', 'd' }; | |
/* How it works: | |
* R is swapped with d | |
* e is swapped with e | |
* v is swapped with s | |
* e is swapped with r | |
*/ | |
// i, j and length are local to the for loop and are initilised only once, as show when debugging. | |
// length is divided by 2 as stated above in the how it works section. | |
// The reason for not having reverse.Length / 2 in the condition part, is math expressions are expensive in loops and should be avoided | |
for (int i = 0, j = reverse.Length - 1, length = reverse.Length / 2; i < length; i++, j--) | |
{ | |
// The char needs to be stored as we loose it in the swapping | |
char temp = reverse[i]; | |
// Swap | |
reverse[i] = reverse[j]; | |
// Now re-add the temp char | |
reverse[j] = temp; | |
} | |
// A way to create a new string from a char array | |
// Notice how it is reversed | |
Console.WriteLine(new string(reverse)); | |
Console.Write("Press any key to continue . . ."); | |
Console.ReadKey(true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment