繁体   English   中英

如何在二维字符串数组中找到特定的字符串?

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

我需要在二维数组中找到一个字符串,但我不知道如何。 该代码应如下所示:

...
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)] = "*";
...

*符号始终位于不同的位置,我想知道如何找到它。 谢谢

您可以像初始化它一样通过遍历数组来找到它,除了不给数组索引赋值,而是检查它是否相等:

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.");

作为使用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();

resultX,Y形式的匹配项列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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