George Brooks
George Brooks

Reputation: 199

Using Linear search

I want to be able to find all the words "Monday" in a file that I read using C#. I can read the file and I can read the first monday and receive its index value but I want the index value of all Mondays in the file.

    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 output it gives is this: // The index is 0 and it does that for each element in the file not just mondays.

Upvotes: 1

Views: 1074

Answers (3)

Andrei Tătar
Andrei Tătar

Reputation: 8295

And something using LINQ and an extension method adapted from another answer:

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

I guess it would be more useful to also have the line number.

Upvotes: 0

chomba
chomba

Reputation: 1441

I want to be able to find all the words "Monday" in a file that I read using C#.

This should work:

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

Upvotes: 1

RagtimeWilly
RagtimeWilly

Reputation: 5445

I think you want to do something like this:

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

You need an inner loop which uses the previous index as the starting point of the search. Otherwise you'll just keep getting the first instance.

Output for "Monday":

The index is 0
The index is 7
The index is 14

Upvotes: 0

Related Questions