我在尝试在C#中的文本文件中查找单词时遇到问题.
我想找到输入到控制台则显示,这个词被发现在整个行字在控制台.
在我的文本文件中,我有:
斯蒂芬哈伦,12月,9,4055551235
Laura Clausing,January,23,4054447788
威廉康纳,12月,13,123456789
卡拉玛丽,十月,23,1593574862
Audrey Carrit,1月16,1684527548
塞巴斯蒂安贝克,十月,23,9184569876
因此,如果我输入"12月",我希望它显示"Stephen Haren,12月,9,4055551235"和"William Connor,12月,13,123456789".
我想过使用子串,但我认为必须有一个更简单的方法.
给出答案后我的代码:
using System;
using System.IO;
class ReadFriendRecords
{
public static void Main()
{
//the path of the file
FileStream inFile = new FileStream(@"H:\C#\Chapter.14\FriendInfo.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
string record;
string input;
Console.Write("Enter Friend's Birth Month >> ");
input = Console.ReadLine();
try
{
//the program reads the record and displays it on the screen
record = reader.ReadLine();
while (record != null)
{
if (record.Contains(input))
{
Console.WriteLine(record);
}
record = reader.ReadLine();
}
}
finally
{
//after the record is done being read, the progam closes
reader.Close();
inFile.Close();
}
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
遍历所有行(StreamReader,File.ReadAllLines等)并检查是否
line.Contains("December")(用用户输入替换"December").
编辑:如果您有大文件,我会使用StreamReader.并使用@Matias Cicero中的IndexOf-Example而不是包含不区分大小写的包含.
Console.Write("Keyword: ");
var keyword = Console.ReadLine() ?? "";
using (var sr = new StreamReader("")) {
while (!sr.EndOfStream) {
var line = sr.ReadLine();
if (String.IsNullOrEmpty(line)) continue;
if (line.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase) >= 0) {
Console.WriteLine(line);
}
}
}
Run Code Online (Sandbox Code Playgroud)