我制作了一个程序,用于在用户输入的句子中查找特定单词。我在C#console应用程序中这样做了。这是完整的代码:
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();
}
}
}
}
}
我已经评论过我在代码中遇到的问题。
答案 0 :(得分:2)
这是因为你正在使用text.Length
而不是words.Length
,你正在查看整个句子的长度,而不是数组中元素的数量。
你最好的选择是对数组做一个foreach,因为你可以真正看到for循环正在做什么。
foreach(string tempWord in words)
{
// put code here
}
请确保您仔细查看这些问题,并使用详细而友好的名称,这样就可以明显地了解您的问题。