【问题标题】:How to implement a simple String search如何实现简单的字符串搜索
【发布时间】:2012-01-12 01:58:27
【问题描述】:

我想根据我的搜索查询在我的应用程序中实现一个简单的搜索。 假设我有一个包含 2 个段落或文章的数组,我想在这些文章中搜索我输入的相关主题或相关关键字。

例如:

//this is my search query
string mySearchQuery = "how to play with matches";

//these are my articles
string[] myarticles = new string[] {"article 1: this article will teach newbies how to start fire by playing with the awesome matches..", "article 2: this article doesn't contain anything"};

如何根据我上面提供的搜索查询获得第一篇文章?有什么想法吗?

【问题讨论】:

    标签: c# .net winforms string search


    【解决方案1】:

    这将返回myarticles 中包含mysearchquery 中所有单词的任何字符串:

    var tokens = mySearchQuery.Split(' ');
    var matches = myarticles.Where(m => tokens.All(t => m.Contains(t)));
    
    foreach(var match in matches)
    {
        // do whatever you wish with them here
    }
    

    【讨论】:

    • 如果使用此技术,您可能希望进行不区分大小写的比较(即匹配匹配匹配)。 ;)
    • 您知道在速度方面与使用正则表达式相比如何吗??
    • 您可以使用 string.ToLower() 进一步改进这一点。那么你就不必担心大小写了。
    【解决方案2】:

    我相信你可以为字符串搜索提供一个不错的框架,因为它是一个广泛的主题,并且有很多搜索规则。

    但是对于这个简单的示例,尝试用“”分割搜索查询,对每个单词做一个简单的字符串搜索,如果找到,在段落搜索匹配中添加 1 点,最后返回最多的段落点...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多