C#C
C#•4y ago
Aksword

How can I modify array values in a for loop ? [Answered]

Hello, I wanted to do a piece of code that replaces half of the words inserted by the user (in a random order) into "train", for example. So I did this :
Random numbergen = new Random();
string answ = Console.ReadLine();
string[] words = answ.Split(' ');
int length = words.Length;
for (int i = 1; i < length/2; i ++)
{
determ :
string target = words[numbergen.Next(0, length - 1)];
string replacer = "train";
if (target == replacer)
{
goto determ;
}
else
{
target = replacer;
}
}
for (int i = 0; i<= length - 1; i ++)
{
Console.Write(words[i] + " ");
}



But when I check what the console print, I see that the words aren't replaced, and then I discovered that when you modify an array in a for loop, it's only modified IN the for loop. So does anyone has a clue to change arrays INSIDE of a for loop and be able to access them OUTSIDE of the loop ?
(Thx 😄 )
Was this page helpful?