简体   繁体   中英

Count number of times a string in my array is found in a text file

I have studied so many answers on Stackoverflow and none do not match what I am trying to achieve.

I have a text file I read in as a single string, I then have an array with multiple entries, I want to scan the text file once for each string in my array and count how many times the string was found in the text file.

My code so far:

string text = System.IO.File.ReadAllText(@"C:\Users\me\Desktop\text.txt");
string[] weekDays = {"Mon","Tue","Wed","Thu","Fri"}
for (int i = 0; i < weekDays.Length; i ++)
{
    // count how often the string is found and output to the console
}

What would be the best approach to doing this? I do not care about speed or efficiency I just need something simple that would work. I tested using regex but I do not think I can do when using an array. Any advice would be much appreciated.

You can do it for all weekdays like this:

 string text = System.IO.File.ReadAllText(@"C:\Users\me\Desktop\text.txt");
 string[] weekDays = {"Mon","Tue","Wed","Thu","Fri"}
 for (int i = 0; i < weekDays.Length; i ++)
        {
             Console.WriteLine (new Regex(weekdays[i]).Matches(text).Count);
        }

How about this with Regex?

Regex regex = new Regex(weekDays[i]);

int count = regex.Matches(text).Count;

If you only need an exact match you can use a "boundary" in your regex:

string[] weekDays = {"Mon", "Tue", "Wed", "Thu", "Fri"};

var searchResult = weekDays
    .Select(s => new Regex($"\\b(?<day>{s})\\b"))
    .SelectMany(r => r.Matches(text).Cast<Match>())
    .GroupBy(m => m.Groups["day"].Value);

foreach (var day in searchResult)
    Console.WriteLine($"Day {day.Key} found {day.Count()} times");

This code will count "Mon" but skip "Monday".

Also if a letter case is not important add a RegexOptions.IgnoreCase option to Regex constructor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM