簡體   English   中英

將字符串從數組轉換為int

[英]Converting string to int from array

我正在嘗試打印出數組元素的確切位置,但結果很短

string[] ocean = { "Beebo", "Jeff","Arthur", "Nemo", "Dory" };

foreach(string fish in ocean)
{
    if (fish == "Nemo")
    {
        Console.WriteLine("We found Nemo on position {0}!",int.Parse(fish));
        return;
    }
}

Console.WriteLine("He was not here");

我需要將 {0} 標記替換為該元素的數組索引,在這種情況下為 3,但我在 int.Parse(fish) 失敗,這顯然不起作用

最簡單的方法是切換到for循環

for(int i = 0; i < ocean.Length; i++)
{
    if (ocean[i] == "Nemo")
    {
        Console.WriteLine("We found Nemo on position {0}!", i);
        return;
    }
}
Console.WriteLine("He was not here");

或者,您可以在foreach跟蹤索引

int index = 0;
foreach(string fish in ocean)
{
    if (fish == "Nemo")
    {
        Console.WriteLine("We found Nemo on position {0}!", index);
        return;
    }

    index++;
}
Console.WriteLine("He was not here");

或者您可以完全避免循環並使用Array.IndexOf 如果未找到該值,它將返回 -1。

int index = Array.IndexOf(ocean, "Nemo");
if(index >= 0)
    Console.WriteLine("We found Nemo on position {0}!", index);
else
    Console.WriteLine("He was not here");

這是一個 Linq 解決方案

var match = ocean.Select((x, i) => new { Value = x, Index = i })
    .FirstOrDefault(x => x.Value == "Nemo");
if(match != null)
    Console.WriteLine("We found Nemo on position {0}!", match.Index);
else
    Console.WriteLine("He was not here");    

我正在 LINQ 中編寫可能的解決方案,我希望它會有所幫助。 該錯誤是由於數組中的索引從零開始它顯示為 3

   string[] ocean = { "Beebo", "Jeff","Arthur", "Nemo", "Dory" };

   ocean.Select((x, i) => new { Value = x, Index = i }).ForEach(element =>
   {
       if (element.Value == "Nemo")
       {
           Console.WriteLine("We found Nemo on position {0}!",element.Index);
       }
   });

如何在編譯器中使用它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM