我正在编写一个要求用户输入单词的应用程序,然后程序会检查字典中较大单词中是否包含任何单词。例如,如果用户输入" starburst",系统将输出" star"和"爆裂"。
我正在程序中创建自己的单词词典。到目前为止,我有一个数组,我只是逐个去,并在字典中添加不同的单词。有没有更有效的方法呢?
下面发布的代码:
static void Main(string[] args) {
Console.WriteLine("Enter a word");
string word = Console.ReadLine();
string word2 = word;
string [] dictionary = new string[300];
dictionary[0] = "apple";
dictionary[1] = "adversary";
dictionary[2] = "apply";
dictionary[3] = "be";
dictionary[4] = "bear";
dictionary[5] = "Bare";
dictionary[6] = "car";
dictionary[7] = "care";
dictionary[8] = "cat";
dictionary[9] = "carreer";
dictionary[10] = "day";
dictionary[11] = "dare";
dictionary[12] = "date";
dictionary[13] = "do";
dictionary[14] = "double";
dictionary[15] = "ex";
dictionary[16] = "extra";
dictionary[17] = "can";
dictionary[18] = "dog";
dictionary[19] = "dont";
for (int i = 0; i < word.Length; i++)
{
for (int n = word2.Length; n < dictionary.Length; n++)
{
if (word == dictionary[n] && word != word2)
{
Console.WriteLine(word);
}
if(word2 == dictionary[n] && word != word2)
{
Console.WriteLine(word2);
}
word.Substring(1, word.Length - 1);
word2.Substring(0, word2.Length - 2);
}
}
}
答案 0 :(得分:0)
有更有效的方法吗?
我认为你的意思是不需要手动更改数组初始化代码,并在想要向字典添加单词时重新编译应用程序。
您可以将单词列表放在一个文件中,然后使用string [] dictionary = File.ReadAllLines("dictionary.txt")
进行阅读。