我正在做一个大学项目,我被如何使用Console.WriteLine打印所有带有前缀("he"(的单词所困扰。这是我到目前为止的代码,正如你所看到的,我已经尝试过了,但它用红色突出显示了我的GetWordsForPrefix("he&"(。谢谢!(别介意其他东西,这是我必须实现的其他场景(
`static void Main(string[]args({列表单词=new List((;
words.Add("car");
words.Add("caramael");
words.Add("hey");
words.Add("hello");
words.Add("helloeverybody");
words.Add("CSC204");
// Console.WriteLine("Scenario 1:");
// Console.WriteLine();
// foreach (string word in words)
// {
// Console.WriteLine(word);
// }
foreach (string word in words.GetWordsForPrefix("he"))
{
Console.WriteLine(word);
}
Console.WriteLine("nScenario 5 Printing all words:");
words.Sort();
Console.WriteLine();
foreach (string word in words)
{
Console.WriteLine(word);
}
Console.WriteLine("n Scenario 6 Insert "car":");
int index = words.BinarySearch("car");
if (index < 0)
{
words.Insert(~index, "car");
}
Console.WriteLine();
foreach (string word in words)
{
Console.WriteLine("Error, This word already exsits");
}
}
}`
如果单词是List,则使用LINQ Where((。
列单词表
List<string> words = new List<string>();
words.Add("car");
words.Add("caramael");
words.Add("hey");
words.Add("hello");
words.Add("helloeverybody");
words.Add("CSC204");
查询单词列表
var results = words.Where( (x) => x.StartsWith("he"));
不清楚是否需要实现名为GetWordsForPrefix
的方法。这个方法显然不是List
属性中的方法。
此外,正如我所评论的,我相信你会在线路上出现错误…
List words = new List();
List
需要某种"类型"的东西。在这种情况下,我假设您需要string
类型…
List<string> words = new List<string>();
然后,要获得列表中所有以"他"开头的单词,可以进行类似…的操作
foreach (string word in words) {
if (word.StartsWith("he")) {
Console.WriteLine(word);
}
}
如果需要实现GetWordsForPrefix
方法,那么该方法将需要一个所有单词的列表和一个字符串"prefix"。然后该方法将返回一个以给定前缀开头的所有单词列表。类似…
private static List<string> GetWordsForPrefix(List<string> allWords, string prefix) {
List<string> prefixWords = new List<string>();
foreach (string word in allWords) {
if (word.StartsWith(prefix)) {
prefixWords.Add(word);
}
}
return prefixWords;
}
然后,您可以用与当前代码类似的方式调用此方法。类似…
foreach (string word in GetWordsForPrefix(words, "he")) {
Console.WriteLine(word);
}