2013-02-22 57 views
1

e.g 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文件的字符串“英格兰”,并返回一个包含该字符串的整条生产线。我如何使用C语言来做到这一点?

回答

2

我会考虑两种方法,大文件(兆字节)和相对较小。

大文件

如果文件较大,包含兆字节的数据:使用流读取器,读取文件取消平铺行尾,analize只是readed串

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

小文件

如果一个文件小,你可以使用帮助器,它返回所有文件内容作为字符串数组 - - (File.ReadAllLines())每行的字符串,然后使用LINQ来搜索子字符串。如果您使用的是.NET 4或更新版本,则可以使用不会读取整个文件并且按读取的操作读取的新助手(File.ReadLines())。

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

,如果你只需要而不是Where(l => l.Contains(pattern))

MSDN第一行使用.FirstOrDefault(l => l.Contains(pattern))

ReadLines和ReadAllLines方法的区别如下:当您使用 ReadLines时,可以在返回整个集合之前开始枚举字符串集合 ;当您使用ReadAllLines时,必须等待返回 数组之前返回整个字符串数组。因此,当您使用非常大的文件时,ReadLines可以更高效。

+0

由于寻找匹配对于解决方案,这里面临的一个挑战是在“Console.Writeline();”中写入的内容这样我就可以在控制台上找到与所需字符串匹配的所有行。 – 2013-02-23 18:03:00

+0

那么写入控制台有什么挑战? – sll 2013-03-05 16:58:38

0

你可以这样做。如果你想返回所有带“england”的行,你需要创建一个字符串列表并返回它。

foreach(string line in File.ReadAllLines("FILEPATH")) 
    { 
    if(line.contains("england")) 
     return line; 
    } 
    return string.empty; 
+0

您好,谢谢您提供解决方案,她想要问的一件事,我可以使用Hashset计数方法具有独特的线条和独特的计数。我试过这段代码,但它不工作: – 2013-02-25 06:46:55

相关问题