index out of range c #

1

I'm trying to do a value assignment on a certain index of a String, however, I get the following error that I do not understand the reason:

  

System.ArgumentOutOfRangeException: 'The index was out of range. It should be non-negative and smaller than the size of the collection. * '

        string tela;
        int counter = 0;
        StringBuilder telaBuilder = new StringBuilder();


        private void btnSendWord_Click(object sender, EventArgs e)
        {
        char letra = Convert.ToChar(txtGetWord.Text);
        Boolean codigoVerificador;
        codigoVerificador =    verificador.VerificaLetra(comboPalavra[0],letra);
        if (codigoVerificador == true)
        {

        foreach(char c in comboPalavra[0].ToCharArray())
           {
                counter = counter + 1;
                if(c == letra)
                {

                    telaBuilder[counter] = Convert.ToChar( letra);
                    tela = telaBuilder.ToString();
                }
            }
       }
    }
    
asked by anonymous 01.10.2017 / 18:47

1 answer

1

You are trying to assign a letter to a position that does not exist in StringBuilder.

To do this, you must initialize the StringBuilder with a number of positions equal to the word you want to find:

private StringBuilder telaBuilder;
private int numeroDeLetras = 10;

...
...
telaBuilder = new StringBuilder(numeroDeLetras);

On the other hand, traditionally, the game usually represents letters not yet found with - .

To do this use

telaBuilder = new StringBuilder(new string('-', numeroDeLetras));

See working at .NET Fiddle

    
01.10.2017 / 19:32