繁体   English   中英

如何获取列表中具有相同前缀的所有单词? C#

[英]How to get all words with the same prefix in a list? C#

我正在做一个大学项目,我很困惑如何使用 Console.WriteLine 打印所有带有前缀(“he”)的单词。 到目前为止,这是我的代码,您可以看到我已经尝试过,但它以红色突出显示了我的 GetWordsForPrefix("he")。 谢谢,(不要介意其他的东西,这是我必须实现的其他场景)

` static void Main(string[] args) { List words = 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");
        }

    }


}` 

如果 words 是 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>();

然后要获得列表中以“他”开头的所有单词,可以 go 之类的东西......

foreach (string word in words) {
  if (word.StartsWith("he")) {
    Console.WriteLine(word);
  }
}

如果您需要实现GetWordsForPrefix方法,那么该方法将需要所有单词的列表和字符串“前缀”。 然后该方法将返回以给定前缀开头的所有单词的列表。 就像是…

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM