簡體   English   中英

搜索特定的字符串並返回整行

[英]Search specific string and return whole line

我想做的是在文本文件中找到字符串的所有實例,然后將包含所述字符串的整行添加到數組中。

例如:

eng    GB    English
lir    LR    Liberian Creole English
mao    NZ    Maori

例如,搜索eng必須將前兩行添加到數組中,當然還要包括文件中更多的'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返回可枚舉的值

一條線:

using System.IO;
using System.Linq;

var result = File.ReadAllLines(@"c:\temp").Select(s => s.Contains("eng"));

或者,如果您想使用內存效率更高的解決方案,則可以使用擴展方法。 您可以使用FileInfoFileStream等作為基本處理程序:

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.Containsline.StartsWith ,因為它似乎在每行開頭所需的詞出現。

您可以嘗試以下代碼,我嘗試過並且它正在工作

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM