Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a simple String search

I want to implement a simple search in my application, based on search query I have. Let's say I have an array containing 2 paragraphs or articles and I want to search in these articles for related subject or related keywords I enter.

For example:

//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"};

How can I get the first article based on the search query I provided above? Any idea?

like image 555
Desolator Avatar asked Dec 03 '11 08:12

Desolator


2 Answers

This would return any string in myarticles that contains all of the words in 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
}
like image 79
Jeff Ogata Avatar answered Oct 02 '22 14:10

Jeff Ogata


I'm sure you can fine a nice framework for string search, cause it's a wide subject, and got many search rules.

But for this simple sample, try splitting the search query with " ", for each word do a simple string search, if you find it, add 1 point to the paragraph search match, at the end return the paragraph with the most points...

like image 20
Chen Kinnrot Avatar answered Oct 02 '22 14:10

Chen Kinnrot