2014-12-24 177 views
0

我需要找到一個二維數組中的字符串,我不知道如何。該代碼應該是這樣的:如何在字符串的二維數組中找到特定的字符串?

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

*符號總是在不同的點,我想知道我怎麼找到它。由於

+0

形式列表您共享的代碼隨機將「*」放在二維數組中,對嗎?然後你需要找到那個「」的位置,對吧? – hmartinezd

+0

如果你有代碼,爲什麼不先用'x.Next(0,10)'和'y.Next(0,10)'設置局部變量,然後使用這些變量來更新數組? – serdar

回答

1

您可以通過就像你初始化它,除了代替分配數組的索引值數組迭代找到它,你會檢查它的平等:

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

@hmartinezd事實上,我認爲你應該看看:http://stackoverflow.com/questions/1659097/why-would-you-use-string-equals-over – itsme86

0

作爲alterntive與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是比賽中的X,Y

相關問題