C# 中的数组搜索引发错误

本文关键字:索引 错误 搜索 数组 | 更新日期: 2023-09-27 18:34:25

我正在玩C#,试图掌握基础知识,但我被这个奇怪的错误难住了。我正在尝试搜索名称数组,然后返回任何匹配项的位置。目前我只是打印名称,但我能够获得位置。

但是由于某种原因,当我键入要搜索的名称并按回车键时,程序崩溃说"ArraySearch.exe已停止工作"。知道怎么了??

请原谅nooby问题,我对这种语言/范式:p仍然很陌生

谢谢! :)

using System;
public class Test
{
    public static void Main()
    {   
        string[] stringArray = {"Nathan", "Bob", "Tom"};
        bool [] matches = new bool[stringArray.Length];
        string  searchTerm = Console.ReadLine();
        for(int i = 1;i<=stringArray.Length;i++){
            if (searchTerm == stringArray[i - 1]){
                matches[i] = true;
            }
        }
        for(int i = 1;i<=stringArray.Length;i++){
            if (matches[i]){
                Console.WriteLine("We found another " + stringArray[i - 1]);
            }
        }
    }
}

C# 中的数组搜索引发错误

i将达到 3,这将在此处给出超出范围的异常:

matches[i] = true;

使用调试很容易发现这一点。(尝试学习使用它。非常有用)

matches 有 3 个元素,因此索引范围从 0 到 2。

using System;
public class Test
{
    public static void Main()
    {
        string[] stringArray = { "Nathan", "Bob", "Tom" };
        bool[] matches = new bool[stringArray.Length];
        string searchTerm = "Bob";
        for (int i = 1; i <= stringArray.Length; i++)
        {
            if (searchTerm == stringArray[i - 1])
            {
                matches[i - 1] = true;
            }
        }
        for (int i = 1; i <= stringArray.Length; i++)
        {
            if (matches[i - 1])
            {
                Console.WriteLine("We found another " + stringArray[i - 1]);
            }
        }
    }
}

请参阅上面的修复程序。它失败了,因为布尔数组在索引 3 中没有项目。3 比其最后一个索引多 1 个索引,即 2。

它的索引是 0,1,2.,它又存储 3 个元素,就像 u 需要的那样。

循环遍历数组时,最好习惯于使用实际索引。所以我建议从 0 循环到 array.length - 1。这样你就可以直接引用数组中的每个元素。

我强烈建议使用lambda进行这种处理。行数少得多,易于理解。

例如:

using System;
using System.Linq;
namespace ConsoleApplication5
{
    public class Test
    {
            public static void Main()
            {
                string[] stringArray = { "Nathan", "Bob", "Tom" };
                bool exists = stringArray.Any(x => x.Equals("Nathan"));
                Console.WriteLine(exists);
            }
     }
}

上面的方法调用 Any() 会为您进行搜索。有很多选择可供探索。您可以将 Any() 替换为 First()、Last() 等。如果我是你,我肯定会探索 System.Linq 库对集合进行此类操作。

(请记住,数组也是一个集合)