I have a string variable. I want to swap the two characters in the string word. I want to randomly swap two characters which are close to each other.
This is what I have done: I have done like this but in some words I get error.
string word = txtWord.Text;
Random rand = new Random();
int randomNumber= rand.Next(0, word.Length);
string swappedWord = SwapCharacters(lastWord, randomNumber, randomNumber + 1);
private string SwapCharacters(string value, int position1, int position2)
{
char[] array = value.ToCharArray(); // Convert a string to a char array
char temp = array[position1]; // Get temporary copy of character
array[position1] = array[position2]; // Assign element
array[position2] = temp; // Assign element
return new string(array); // Return string
}
rand.Next(0, word.Length - 1);randomNumber + 1