A Swap method exchanges array element values. It acts on 2 separate elements so that they both are still present but in opposite locations.
In the C# language, there is no built-in method for this purpose on most types. You have to implement a custom swap method for string
characters and other types.
This example shows how to swap two characters in a string
's character buffer. It also shows how to swap two elements in an array with elements of type Int32
.
SwapCharacters
, we use the ToCharArray
method and the new string
constructor and return a new string
reference.string
type is immutable and you cannot assign characters to locations in a string
directly.SwapInts
, the code uses a temporary variable, but the int
array is modified in-place so no reference must be returned.using System; class Program { static void Main() { // Swap characters in the string. string value1 = "abc"; string swap1 = SwapCharacters(value1, 0, 1); Console.WriteLine(swap1); // Swap elements in array. int[] array1 = { 1, 2, 3, 4, 5 }; SwapInts(array1, 0, 1); foreach (int element in array1) { Console.Write(element); } Console.WriteLine(); } static string SwapCharacters(string value, int position1, int position2) { // Swaps characters in a string. char[] array = value.ToCharArray(); char temp = array[position1]; array[position1] = array[position2]; array[position2] = temp; return new string(array); } static void SwapInts(int[] array, int position1, int position2) { // Swaps elements in an array. int temp = array[position1]; array[position1] = array[position2]; array[position2] = temp; } } bac 21345
This code will cause exceptions if you call it with invalid parameters. If needed, you can validate the arguments with if
-statements and then throw.
It is possible to develop methods that swap characters in a string
or elements in an array. These methods were tested and proven correct on the input provided.