apo*_*his 13 .net c# string-search
我想要做的是在文本文件中找到字符串的所有实例,然后将包含所述字符串的完整行添加到数组中.
例如:
eng GB English
lir LR Liberian Creole English
mao NZ Maori
Run Code Online (Sandbox Code Playgroud)
例如,搜索eng必须将前两行添加到数组中,当然包括文件中的更多"eng"实例.
如何使用文本文件输入和C#完成此操作?
Bek*_*pov 18
你可以使用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者你可以yield return用来返回连词
aba*_*hev 10
一条线:
using System.IO;
using System.Linq;
var result = File.ReadAllLines(@"c:\temp").Select(s => s.Contains("eng"));
Run Code Online (Sandbox Code Playgroud)
或者,如果您想要更高效的内存解决方案,可以使用扩展方法.您可以使用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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
var result = new FileInfo(path).ReadAndFilter(s => s.Contains("eng"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33607 次 |
| 最近记录: |