C#单词查找器错误

本文关键字:错误 查找 单词 | 更新日期: 2023-09-27 18:21:29

我制作了一个程序,可以在用户输入的句子中找到特定的单词。我在C#控制台应用程序中做到了这一点。这是整个代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Word_finder_control_assessment_test
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] delimiterChars = { ' ', ',', '.', ':', ''t' };
            Console.WriteLine("Please enter a sentence ");
            Console.ForegroundColor = ConsoleColor.Blue;
            string text = Convert.ToString(Console.ReadLine().ToLower());

            string[] words = text.Split(delimiterChars);
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("'nPlease enter the word to find");
            Console.ForegroundColor = ConsoleColor.White;
            string wordtofind = Convert.ToString(Console.ReadLine().ToLower());

            for (int position = 0; position < text.Length; position++)
            {
                string tempword = words[position]; // at the end of this application this is highlighted yellow and an error returns : Index was outside the bounds of the array. My application works perfectly except for that.
                if (wordtofind == tempword)
                {

                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("The position of the word is {0} ", position + 1);
                    Console.ReadLine();
                }
                    }
                }
            }
        }

我已经评论了我在代码中遇到的问题。

C#单词查找器错误

这是因为您使用的是text.Length而不是words.Length,您查看的是整个句子的长度,而不是数组中的元素数量。

你最好在数组上做一个foreach,因为你可以真正看到for循环在做什么。

foreach(string tempWord in words)
{
    // put code here
}

请确保您正在密切关注这类问题,并使用详细友好的名称,这样您就可以清楚地了解循环的内容。