繁体   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