计算在文本文件中发现数组中的字符串的次数

时间:2018-09-24 18:59:15

标签: c# regex string substring

我研究了很多关于Stackoverflow的答案,但没有一个与我要达到的目标不符。

我有一个以单个字符串形式读取的文本文件,然后有一个具有多个条目的数组,我想为数组中的每个字符串扫描一次文本文件,并计算在该字符串中找到该字符串的次数。文本文件。

到目前为止,我的代码:

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
}

执行此操作的最佳方法是什么?我不在乎速度或效率,我只需要简单的方法就可以了。我使用正则表达式进行了测试,但是使用数组时我不认为可以。 任何建议将不胜感激。

3 个答案:

答案 0 :(得分:4)

您可以像这样在所有工作日这样做:

 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);
        }

答案 1 :(得分:2)

使用Regex怎么样?

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

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

答案 2 :(得分:2)

如果只需要完全匹配,则可以在正则表达式中使用“边界”:

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");

此代码将计为“星期一”,但跳过“星期一”。

如果字母大小写不重要,请向RegexOptions.IgnoreCase构造函数添加Regex选项