我正在尝试搜索一个数组以查找另一个较小的数组值。我使用了嵌套循环,找到的值完美显示。但是,我还想打印未找到的值,任何人都可以帮助我改进我的代码,以便在循环中打印未找到的值,而不像我在代码中那样使用文字(代码块//改进代码)
希望大家能帮忙。
( class Program
{
static void Main(string[] args)
{
int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98};
int[] searchValues = { 0, 25, 99, 12, 3 };
for (int i = 0; i < searchValues.Length; ++i)
{
for (int j = 0; j< intArray.Length; ++j)
{
if (searchValues[i]== intArray[j])
{
Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", searchValues[i], j);
}
}
// improve the code
if (i == 1 || i == 2)
{
Console.WriteLine("The Value {0} was Not found in intarray ", searchValues[i]);
}
}
Console.Read();
}
})
最佳答案
如果你在 foreach 上交换嵌套循环,你可以使代码更具可读性和 IndexOf功能。代码如下:
int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98 };
int[] searchValues = { 0, 25, 99, 12, 3 };
foreach (var arr in searchValues)
{
int index = Array.IndexOf(intArray, arr);
if (index != -1)
Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", arr, index);
else
Console.WriteLine("The Value {0} was Not found in intarray ", arr);
}
Console.ReadKey();
关于c# - C# 中的数组搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083530/