3

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 ");
}
3
  • 1
    Can you please show the code that defines Arr. Is it a string[][] or a string[,]? Commented Oct 3, 2014 at 13:23
  • ln.Equals(Arr) Compares a string with an array and will always return false Commented Oct 3, 2014 at 13:24
  • here's the code string[,] Arr = new string[4,5] { {"A1" , " A2" , " A3" , " A4" , " A5"}, {"B1" , " B2" , " B3" , " B4" , " B5"}, {"C1" , " C2" , " C3" , " C4" , " C5"}, {"D1" , " D2" , " D3" , " D4" , " D5"}, };` Commented Oct 3, 2014 at 13:24

4 Answers 4

3

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";
Sign up to request clarification or add additional context in comments.

Comments

0

This should do the trick:

   string ln = Console.ReadLine();
   for (int i = 0; i < Arr.length; i++) {
        Arr[i] = Arr[i].Replace(ln, "X ");
   }

Comments

0
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);
    }
}

Comments

0

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";
             }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.