EM10
EM10

Reputation: 815

How do I swap two characters in a string variable?

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
}

Upvotes: 1

Views: 8745

Answers (4)

user3386894
user3386894

Reputation: 46

Try this code. It is easiest to change your code

int randomNumber= rand.Next(0, word.Length-2);

Upvotes: 0

Bhupendra Shukla
Bhupendra Shukla

Reputation: 3914

Use a StringBuilder:

//If you want to replace

StringBuilder sb = new StringBuilder(theString);
    sb[index] = newChar;
    theString = sb.ToString();

//Swap

 string input = "AXBYCZ"; //Sample String
    StringBuilder output = new StringBuilder();

    char[] characters = input.ToCharArray();

    for (int i = 0; i < characters.Length; i++)
    {
      if (i % 2 == 0)
      {
        if((i+1) < characters.Length )
        {
          output.Append(characters[i + 1]);
        }
                   output.Append(characters[i]);
      }
    }

Upvotes: 3

pareto
pareto

Reputation: 196

Just change the line as below:

int randomNumber= rand.Next(0, word.Length -1 );

Let's see if it works.

Upvotes: 1

bit
bit

Reputation: 4487

Try this. Also add checks if the word is empty.

int randomNumber= rand.Next(0, word.Length - 1);

Upvotes: 0

Related Questions