Reputation:
I have 3 text files namely
input.txt
array1.txt
array2.txt
input.txt file consist of lines like:
the file in
the computer is
removedby user,
there are seven
wonders in the world
ithink...
array1.txt file consist of:
computer
user
good
array2.txt file consist of:
seven
world
none
I want to check the presence of words in input.txt with the array1.txt and array2.txt
what I am trying to say is eg: the word in input.txt is match with the word in array1.txt means output must be "computer" is present in array1. if the word match with array2.txt means it should show the word present in array2.
output: words computer and user is present in array1 words world and seven is present in array2
my code in c#:
int count;
using (StreamReader reader = File.OpenText("C:/Users/input.txt"))
{
string contents = reader.ReadToEnd();
MatchCollection matches = Regex.Matches(contents, "computer", RegexOptions.IgnoreCase);
count = matches.Count;
}
if (count > 0)
{
MessageBox.Show("present");
}
else
{
MessageBox.Show("absent");
}
Upvotes: 2
Views: 317
Reputation: 37299
I'd go for a different approach:
File.ReadAllText
or File.ReadAllLines
.Contains
instead of regex.Where
method to check a predicate for each item in the arraySo:
var arr1 = File.ReadAllLines("array1.txt"); // Reading to get string[] - item for each line
var arr2 = File.ReadAllLines("array2.txt");
var input = File.ReadAllText("input.txt"); // Reading to get one string for all text
var arr1WordsInInput = arr1.Where(input.Contains);
var arr2WordsInInput = arr2.Where(input.Contains);
If you want to find all indexes of matches you can use function proposed in answer for this question Finding ALL positions of a substring in a large string in C# like this:
var result = arr1.Select(w => new { Word = w, Indexes = input.AllIndexesOf(w) })
.Where(w => w.Indexes.Any());
This will return an IEnumerable
where each item contains two properties: the matching word and the indexes where it was found within the input
text
Upvotes: 1