C#でテキストファイル内の単語を検索しようとして問題が発生しました。
私はその単語がで見つかったことを、行全体を表示コンソールに入力されている単語検索するには、コンソールを。
私のテキストファイルには次のものがあります。
スティーブン・ハーレン、12月9,4055551235
ローラ・クラウジング、1月23,4054447788
ウィリアム・コナー、12月13,123456789
カラマリー、10月23,1593574862
オードリー・キャリット、1月16,1684527548
セバスチャン・ベイカー、10月23,9184569876
したがって、「December」と入力すると、「Stephen Haren、December、9,4055551235」と「WilliamConnor、December、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();
}
}
すべての行(StreamReader、File.ReadAllLinesなど)を繰り返し処理し、line.Contains("December")
(「December」をユーザー入力に置き換えます)かどうかを確認します。
編集:大きなファイルがある場合は、StreamReaderを使用します。また、大文字と小文字を区別しない場合は、containsの代わりに@MatiasCiceroの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);
}
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加