gpt4 book ai didi

c# - 将字符串从数组转换为 int

转载 作者:行者123 更新时间:2023-12-02 03:01:17 26 4
gpt4 key购买 nike

我试图打印出数组元素的确切位置,但结果很短

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

关于c# - 将字符串从数组转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59919121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com