title: How to get index of all matching chars in char array?
body: <p>I am working on a simple hangman program. I have most of the code working, but I am having trouble figuring out how to get the index of multiple matching chars in a char array. For example, I have a word "sushi" converted to a char array. If the user guesses an "s" then all "s" in the char array should be shown. The way that my code is, I actually have two char arrays of the same length. The first array holds the chars of the word to guess, while the second array holds question marks. My code should iterate through the first array and return the index of <em>each</em> element in the array that matches the user guess. Then, the code inserts the user guess at each specified index and displays the second array for the user. Unfortunately, only the first occurrence is changed in the second array, so only the first index is returned from the match query. The problematic code is as follows:</p>
  
  <pre><code>            //check if char array contains the user input
              if (guessThis.Contains(Convert.ToChar(textBox1.Text)))
              {
                  //save user input as char
                  char userGuess = Convert.ToChar(textBox1.Text);
                  //iterate through first char array
                  for (int i = 0; i &lt; guessThis.Length - 1; i++ )
                  {
                      //check each element in the array
                      //probably don't need both for and foreach loops
                      foreach (char c in guessThis)
                      {
                          //get index of any element that contains the userinput
                          var getIndex = Array.IndexOf(guessThis, c);
                          //check if the element matches the user guess
                          if (c == userGuess)
                          {
                              //insert the userguess into the index
                              displayAnswer[getIndex] = userGuess;
  
                          }
                      }
  
                  }
                  //update the display label
                  answerLabel.Text = new string(displayAnswer);
  </code></pre>
  
  <p>SOLVED:
  Working off of the example in the selected answer, I updated my code as:</p>
  
  <pre><code>                //check if char array contains the user input
              if (guessThis.Contains(Convert.ToChar(textBox1.Text)))
              {
                  //save user input as char
                  char userGuess = Convert.ToChar(textBox1.Text);
                  string maybeThis = textBox1.Text;
                  string tryThis = new string(guessThis);
                  foreach (Match m in Regex.Matches(tryThis, maybeThis))
                  {
                      displayAnswer[m.Index] = userGuess;
                  }
                  answerLabel.Text = new string(displayAnswer);
              }
  </code></pre>