2011-12-03 35 views
5

我想在我的應用程序中實現一個簡單的搜索,基於我擁有的搜索查詢。 比方說,我有一個數組包含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"}; 

我怎樣才能根據我上面提供的搜索查詢的第一篇文章?任何想法?

回答

6

這將在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 
} 
+0

你可能會想要做一個不區分大小寫的比較,如果使用這樣的技術(即如此比賽比賽)。 ;) –

+0

你知道在速度方面,用正則表達式怎麼比較? – GameAlchemist

+0

你可以通過使用string.ToLower()來進一步改進。那麼你不必擔心大寫。 –

1

我敢肯定,你可以罰款一個漂亮的字符串搜索框架,因爲它是一個廣泛的主題,並獲得了許多搜索規則。

但是對於這個簡單的示例,試着用「」分割搜索查詢,對於每個單詞做一個簡單的字符串搜索,如果找到它,則在段落搜索匹配中添加1個點,最後返回帶有最高分......

相關問題