C#单词查找器错误
我制作了一个程序,在用户输入的句子中查找特定的单词。我是在C#控制台应用程序中完成的。以下是全部代码:C#单词查找器错误,c#,arrays,console-application,C#,Arrays,Console Application,我制作了一个程序,在用户输入的句子中查找特定的单词。我是在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 { s
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();
}
}
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间单词查找器控制评估测试
{
班级计划
{
静态void Main(字符串[]参数)
{
char[]delimiterChars={',',',',':','\t'};
Console.WriteLine(“请输入一个句子”);
Console.ForegroundColor=ConsoleColor.Blue;
字符串文本=Convert.ToString(Console.ReadLine().ToLower());
string[]words=text.Split(delimiterCars);
Console.ForegroundColor=ConsoleColor.White;
Console.WriteLine(“\n请输入要查找的单词”);
Console.ForegroundColor=ConsoleColor.White;
string wordtofind=Convert.ToString(Console.ReadLine().ToLower());
对于(int位置=0;位置
我已经对代码中的问题进行了注释。这是因为您使用的是
text.Length
而不是words.Length
,您查看的是整个句子的长度,而不是数组中的元素数
最好的办法是在数组上执行foreach,因为您可以真正看到for循环在做什么
foreach(string tempWord in words)
{
// put code here
}
请确保您正在仔细研究这类问题,并使用冗长友好的名称,以便清楚地知道您在循环什么。请在我的代码中演示一下这一点好吗?为了简单起见,如果您正在查看代码,则需要将(int position=0;position
更改为(int position=0;positionfor(int position=0;positiontext.Length
将等于19,但words.Length
将等于4,这是您在使用位置作为单词的索引时希望看到的,而不是text
,这不是一个问题,只要确保您理解is不起作用的原因,这似乎是一个学校项目,作为一名新程序员,您应该确保完全理解这些运行时错误,很容易忽略类似的内容,或者在if语句中使用错误的符号。使用注释提供帮助,如前所述,使用有用的命名约定,如果将text
改为userInput
,很容易看出您不应该查看userInput
,而应该查看单词数组