Reputation: 187
I'm trying to replace a string value in a 2d array and tried this codes below but nothing is happening
foreach (string item in Arr)
{
if (UserInput.Equals(item))
{
item.Replace(UserInput, "X ");
}
}
and the same goes for this codes nothing is happening...
Console.WriteLine("Select a seat that you want to ocupy");
string ln = Console.ReadLine();
if (ln.Equals(Arr))
{
ln = ln.Replace(ln, "X ");
}
Upvotes: 3
Views: 2389
Reputation: 1079
Try this:
string[,] Arr = new string[4, 5];
string textToReplace = "test";
for(int k=0;k < Arr.GetLength(0);k++)
for(int l=0;l < Arr.GetLength(1);l++)
if (Arr[k,l]==textToReplace){
Arr[k, l] = "X";
}
Upvotes: 0
Reputation: 186728
Your current code
item.Replace(UserInput, "X ");
creates new String
which you then ignore; it could have been something like
item = item.Replace(UserInput, "X ");
However, that's impossible within foreach loop, so let's try for loops:
String[,] Arr = new String[,] {
{"A1", "A2", "A3", "A4"},
{"B1", "B2", "B3", "B4"}
};
String UserInput = "B3";
for(int line = Arr.GetLowerBound(0); line <= Arr.GetUpperBound(0); ++line)
for(int column = Arr.GetLowerBound(1); column <= Arr.GetUpperBound(1); ++column)
if (Arr[line, column].Contains(UserInput))
Arr[line, column] = "X";
Upvotes: 3
Reputation: 7273
if (ln.Equals(Arr))
{
ln = ln.Replace(ln, "X ");
}
What is Arr ? is it Array Object?
If it yes, You can't just make equals with the whole array
you need to check each of it by using for loop or something
for (int i=0, len = Arr.Length; i < len; i++ )
{
if (ln.Equals(Arr[i]))
{
Console.WriteLine("old ln = " + ln);
ln = ln.Replace(ln, "X ");
Console.WriteLine("new ln = " + ln);
}
}
Upvotes: 0
Reputation: 23029
This should do the trick:
string ln = Console.ReadLine();
for (int i = 0; i < Arr.length; i++) {
Arr[i] = Arr[i].Replace(ln, "X ");
}
Upvotes: 0