我想要做的是在文本文件中查找字符串的所有實例,然後將包含所述字符串的完整行添加到數組中。搜索特定字符串並返回整行
例如:
eng GB English
lir LR Liberian Creole English
mao NZ Maori
搜索ENG,例如,必須在第一兩行添加到陣列中,當然也包括在該文件中的「主機」的許多更多的實例。
這是怎麼做到的,使用文本文件輸入和C#?
我想要做的是在文本文件中查找字符串的所有實例,然後將包含所述字符串的完整行添加到數組中。搜索特定字符串並返回整行
例如:
eng GB English
lir LR Liberian Creole English
mao NZ Maori
搜索ENG,例如,必須在第一兩行添加到陣列中,當然也包括在該文件中的「主機」的許多更多的實例。
這是怎麼做到的,使用文本文件輸入和C#?
可以使用的TextReader將讀取每一行,並進行搜索,如果發現ü想要什麼,然後添加一行到字符串數組
List<string> found = new List<string>();
string line;
using(StreamReader file = new StreamReader("c:\\test.txt"))
{
while((line = file.ReadLine()) != null)
{
if(line.Contains("eng"))
{
found.Add(line);
}
}
}
,或者您可以使用yield return
返回enumurable
你可以試試下面的代碼,我嘗試過了,這是工作
string searchKeyword = "eng";
string fileName = "Some file name here";
string[] textLines = File.ReadAllLines(fileName);
List<string> results = new List<string>();
foreach (string line in textLines)
{
if (line.Contains(searchKeyword))
{
results.Add(line);
}
}
一號線:
using System.IO;
using System.Linq;
var result = File.ReadAllLines(@"c:\temp").Select(s => s.Contains("eng"));
或者,如果你想更多的內存高效的解決方案,你可以滾的擴展方法。可以使用FileInfo
,FileStream
等作爲鹼處理程序:
public static IEnumerable<string> ReadAndFilter(this FileInfo info, Predicate<string> condition)
{
string line;
using (var reader = new StreamReader(info.FullName))
{
while ((line = reader.ReadLine()) != null)
{
if (condition(line))
{
yield return line;
}
}
}
}
用法:
var result = new FileInfo(path).ReadAndFilter(s => s.Contains("eng"));
的File
對象包含一個靜態ReadLines
方法返回線由行,與此相反用ReadAllLines
它返回一個數組,因此需要將完整的文件加載到內存中。
所以,通過使用File.ReadLines
和LINQ高效和短溶液可以寫成:
var found = File.ReadLines().Where(line => line.Contains("eng")).ToArray();
對於原來的問題,它可以被進一步通過用line.StartsWith
替換line.Contains
優化,因爲它似乎所需術語出現在每行的開頭。