- Course
- Text Files A
- Search lines in a text file
Search lines in a text file
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a C# program that reads the contents of a text file and stores it in an array of strings.
Then ask the user for words or phrases until you enter an empty text. Each time the user enters a word or phrase, it shows the lines that match the text, provided it is not empty.
Input
Output
vulputate himenaeos. Venenatis dapibus congue quis aptent tincidunt vivamus
fermentum eu libero eros nullam varius curabitur, ligula et sem sapien eget fringilla
euismod justo sociis malesuada aliquet leo pretium nullam ullamcorper vitae nostra mi
Solution
using System;
using System.IO;
public class SearchLinesInFile
{
public static void Main(string[] args)
{
string fileName = "input.txt";
string[] lines = File.ReadAllLines(fileName);
bool exit = false;
do
{
string line = Console.ReadLine();
if (line != "")
{
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains(line))
{
Console.WriteLine(lines[i]);
}
}
}
else
{
exit = true;
}
}
while (!exit);
}
}