0

this is my array,

public String[] Swears = new string[22] {"bad words"}

there are 22 swear words included in this, not gonna put them here. this works perfectly but doesnt seem to work in the forloop

this is the text box that the user inputs their name into, and it includes a remove statement that doesnt seem to work. when this code runs, it can only remove the first 4 swears, but the swears after that cause an error

public void player1Name_TextChanged(object sender, EventArgs e)
    {
        for(int i =0; i<22; i++)
        {
           
            if (player1Name.Text == Swears[i])
            {
                int o = player1Name.Text.Length;
                player1Name.Text = (Swears[i].Remove(4));
                MessageBox.Show("please enter a valid Name");
            }
        }
       
    }
Pango661
  • 1
  • 2
  • i should clarify that the remove was originally Remove(i) and it still just didnt work – Pango661 Jun 13 '21 at 14:12
  • I have a hard time seeing your intent from your code. Can you explain what it is you want it to do? Also, your `o` variable is never used. – Hans Kilian Jun 13 '21 at 14:17
  • the code is designed to remove any instances of swears that are entered into the textbox. for instance, if f*** is entered, it immediatedly removes that text, and outputs "please enter a valid name". the o variable was added with the intent of using it as a way to remove the number of characters that were added but that didnt work. so the intent is to use the loop to remove any swears that match to the ones in the array – Pango661 Jun 13 '21 at 14:21
  • 1
    This is a classic problem with for loop. Removing elements from the collection that you are iterating over creates problems in keeping the index variable accurate. The solution is easy: Do your loop starting from the end going toward the start. _for(int i =21; i>=0; i--)_ – Steve Jun 13 '21 at 14:49
  • 1
    I think this code is completely wrong `if (player1Name.Text == Swears[i])` should be `if (player1Name.Text.Contains(Swears[i]))` and `player1Name.Text = (Swears[i].Remove(4));` should be `player1Name.Text = player1Name.Text.Replace(Swears[i], "");` and therefore the dupe linked by @Steve is wrong as it's not anymore relevant – Charlieface Jun 13 '21 at 15:38

0 Answers0