2010-11-22 29 views
1

我有名稱的文本文件作爲balamurugan,chendurpandian,...... 如果我給在文本框中爲ba ....搜索文本文件裏的關鍵字

的值。如果我點擊提交按鈕意味着我必須搜索文本文件對於值ba而顯示爲pattern matched ....

我已閱讀使用

string FilePath = txtBoxInput.Text; 

文本文件,並使用

0123顯示它在一個文本框
textBoxContents.Text = File.ReadAllText(FilePath); 

但我不知道如何在一個文本文件中使用c#搜索一個單詞任何人都可以給建議?

回答

2

您可以簡單地使用:

textBoxContents.Text.Contains(keyword) 

這將返回true如果您的文本包含您選擇的關鍵字。

2

取決於您需要的模式匹配類型 - 您可以使用String.Contains方法這樣簡單的方法,也可以嘗試使用正則表達式,這樣可以更好地控制您想要如何搜索並同時給出所有匹配。這裏有幾個環節讓你在正則表達式快速入門:

http://www.codeproject.com/KB/dotnet/regextutorial.aspx http://www.developer.com/open/article.php/3330231/Regular-Expressions-Primer.htm

2

第一,你應該分手了輸入字符串,之後,你可以做一個包含每個值:

// On file read: 
String[] values = File.ReadAllText(FilePath); 

// On search: 
List<String> results = new List<String>(); 
for(int i = 0; i < values.Length; i++) { 
    if(values[i].Contains(search)) results.Add(values[i]); 
} 

另外,如果你只希望它在開頭或字符串的結尾進行搜索,您可以使用StartsWith或EndsWith,分別爲:

// Only match beginnging 
values[i].StartsWith(search); 
// Only match end 
values[i].EndsWith(search);