简体   繁体   中英

How to find a particular string in a two dimensional array of string?

I need to find a string in a two dimensional array and I don't know how. The code should look like this:

...
Random x = new.Random();
Random y = new.Random();
string[,] array = new string[10,10];
{
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            array[i, j] = "";
        }
    }
}
array[x.Next(0,10),y.Next(0,10)] = "*";
...

The * symbol is always in a different spot and I'd like to know how do I find it. Thanks

You can find it by iterating through the array just like you did for initializing it, except instead of assigning the array index a value, you'll check it for equality:

int i = 0;
int j = 0;
bool found = false;

for (i = 0; i < 10 && !found; i++)
{
    for (j = 0; j < 10; j++)
    {
        if (array[i, j] == "*")
        {
            found = true;
            break;
        }
    }
}

if (found)
    Console.WriteLine("The * is at array[{0},{1}].", i - 1, j);
else
    Console.WriteLine("There is no *, you cheater.");

As an alterntive search query with LINQ :

Random xRnd = new Random(DateTime.Now.Millisecond);
Random yRnd = new Random(DateTime.Now.Millisecond);

string[,] array = new string[10, 10];

array[xRnd.Next(0, 10), yRnd.Next(0, 10)] = "*";

var result = 
    Enumerable.Range(0, array.GetUpperBound(0))
    .Select(x => Enumerable.Range(0, array.GetUpperBound(1))
        .Where(y => array[x, y] != null)
        .Select(y => new { X = x, Y = y }))
    .Where(i => i.Any())
    .SelectMany(i => i)
    .ToList();

result is a list of matches in the form of X,Y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM