1

たとえば、txt ファイルには次のエントリがあります。

england is cold country
India is poor country
england is cold country
england is cold country
India is poor country
english county cricket season.

このtxtファイルで文字列「england」を検索し、この文字列を含む行全体を返したいと思います。Cシャープ言語を使用してどのように行うことができますか?

4

3 に答える 3

2

I would consider two approaches, for large file (megabytes) and for relatively small.

Large File

If file is large and contains megabytes of data: use stream reader, read file untile EndOfLine, analize just readed string

string pattern = "england";
IList<string> result = new List<string>();
using (var reader = new StreamReader("TestFile.txt")) 
{
    string currentLine;
    while ((currentLine= reader.ReadLine()) != null) 
    {
        if (currentLine.Contains(pattern)
        {
            // if you do not need multiple lines and just the first one
            // just break from the loop (break;)            
            result.Add(currentLine);
        }
    }
}

Small file

If a file is small you can use helper which returns all file content as array of strings - (File.ReadAllLines()) string per line and then use LINQ to search for substring. if you are using .NET 4 or newer you can leverage new helper (File.ReadLines()) which does not read entire file and does read as deffered operation.

.NET 2.0 - 3.5:

string pattern = "england";
IEnumerable<string> result = File.ReadAllLines()
                                 .Where(l => l.Contains(pattern));

.NET4 - 4.5:

string pattern = "england";
IEnumerable<string> result = File.ReadLines()
                                 .Where(l => l.Contains(pattern));

if you need just the first line use .FirstOrDefault(l => l.Contains(pattern)) instead of Where(l => l.Contains(pattern))

MSDN:

The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

于 2013-02-22T11:40:38.790 に答える
0

You can do it like. If you want to return all lines with "england" you need to create a list of strings and return this.

foreach(string line in File.ReadAllLines("FILEPATH"))
    {
    if(line.contains("england"))
       return line;
    }
    return string.empty;
于 2013-02-22T11:40:41.367 に答える
0

1) すべての行を読み取ります。http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx

2)文字列のリストを作成して一致を入力します

3) 行をループまたは linq し、IndexOf(matchstring) > -1 を使用して一致を探します

4) 結果を返す

于 2013-02-22T11:41:48.063 に答える