1

我希望能够在我使用 C# 读取的文件中找到所有单词“Monday”。我可以读取文件,我可以读取第一个星期一并接收它的索引值,但我想要文件中所有星期一的索引值。

    if (ElementS == "2")
    {
        Console.WriteLine("Enter The name of the day e.g. Monday, Tuesday   etc.");
        string ElementA =  Convert.ToString(Console.ReadLine());



        foreach (string Monday in DayLines)
        {
        string Mday = "Monday";
        int Found = Search(DayLines, Mday);
        Console.WriteLine("The index is {0}", Found);
        }

它给出的输出是这样的: // The index is 0 它对文件中的每个元素都这样做,而不仅仅是星期一。

4

3 回答 3

1

我希望能够在我使用 C# 读取的文件中找到所有单词“Monday”。

这应该有效:

static void Main()
{
    string text = File.ReadAllText(@"e:\1.txt");
    Regex regex = new Regex("Monday", RegexOptions.IgnoreCase);
    Match match = regex.Match(text);

    while (match.Success)
    {
        Console.WriteLine("'{0}' found at index {1}", match.Value, match.Index);
        match = match.NextMatch();
    }
}
于 2015-04-22T05:10:45.263 回答
0

还有一些使用 LINQ 和从另一个答案改编的扩展方法的东西:

static class Extensions
{
    public static IEnumerable<int> AllIndexesOf(this string str, string value)
    {
        for (var index = 0; ; index += value.Length)
        {
            index = str.IndexOf(value, index, StringComparison.Ordinal);
            if (index == -1)
                yield break;
            yield return index;
        }
    }
}

...

var allMondayIndexes = File
            .ReadAllLines("input.txt")
            .SelectMany(s => s.AllIndexesOf("Monday"));

我想还有行号会更有用。

于 2015-04-22T05:47:07.210 回答
0

我想你想做这样的事情:

internal static void Main(string[] args)
{
    var dayLines = new List<string>()
        {
            "Monday Monday Monday",
            "Tuesday"
        };

    var dayToFind = Console.ReadLine();

    foreach (var line in dayLines.Where(l => l.Contains(dayToFind)))
    {
        var index = -1;
        do
        {
            index = line.IndexOf(dayToFind, index + 1);

            if (index > -1)
                 Console.WriteLine("The index is {0}", index);
        }
        while (index > -1);
    }

    Console.ReadLine();
}

您需要一个使用前一个索引作为搜索起点的内部循环。否则,您将继续获得第一个实例。

“星期一”的输出:

The index is 0
The index is 7
The index is 14
于 2015-04-22T03:50:27.350 回答