1

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
}
5
  • 4
    Try rand.Next(0, word.Length - 1); Commented Mar 6, 2014 at 6:57
  • What is the error you are getting? Commented Mar 6, 2014 at 6:57
  • @L.B wasn't the higher bound non-inclusive? Commented Mar 6, 2014 at 6:58
  • 2
    @MarioStoilov see the next line randomNumber + 1 Commented Mar 6, 2014 at 6:59
  • @L.B ah, yes. Didn't see that one. Commented Mar 6, 2014 at 7:00

4 Answers 4

3

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]);
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

1

Just change the line as below:

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

Let's see if it works.

3 Comments

When I do this. I get it right but if the word is only 1 character I will get errors when I change the position of the word in the swapCharaters() method.
This is so because there is only one character in the string and in your method you are passing 'randomNumber+1' as well. Just put a check before it that says
if (randomNumber < word.Length -1) string swappedWord = SwapCharacters(lastWord, randomNumber, randomNumber + 1); else string swappedWord = SwapCharacters(lastWord, randomNumber, randomNumber); I hope this will help.
0

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

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

Comments

0

Try this code. It is easiest to change your code

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.