-3

i've got a little question..

i have a simple txt file with some lines in it, but i struggle with something : the text file is linked to 3 methods by example :

method 1 calls : "callMath", 2: "callFrench" and 3: "callDutch".

the text file looks like this by example:

math_tafels_question1

dutch_dt_question1

french_vocab_question1

math_tafels_question2

dutch_dt_question2

french_vocab_question2

etc etc..

my question is is there something like a substring command or something that if i call the method "callMath" that it only reads the lines that start with "math?" and if i call the method "callFrench" it only reads the lines that start with "french"?

you may say sort them and read them per 10 or something, but the thing is some questions will be deleted, and there will be some questions added, so i never know the exact line number of the questions..

hope anyone can help me out?;)

Andres
  • 11
  • 1
  • 1
    So what have you come up with already? Have you encountered `System.IO.File.ReadAllLines` yet? This question could be a simple "for each line apply a regex or something", or it could be "abstract each line processor into a Strategy and have each implementation scan the file for pertinent lines and process them". – Adam Houldsworth Apr 16 '15 at 10:29
  • The question shows somehow a lack of basic programming knowledge. – Ignacio Soler Garcia Apr 16 '15 at 10:35

2 Answers2

3

That doesn't look like a very well-thought out file format, but I guess you'll have to live with it.

It's trivial what you want to do though:

var relevantLines = File.ReadLines(filename)
                        .Where(l => l.StartsWith("math_"));

This will give you an IEnumerable<string> with all lines from filename that start with "math_".

See also What's the fastest way to read a text file line-by-line?, How to check if a word starts with a given character?.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • @Ignacio yeah I miss the "too localized" close reason. It's a duplicate of a combination of both questions I linked to, so I can't close as duplicate either. – CodeCaster Apr 16 '15 at 10:35
0

You're probably looking for the StartsWith() method. Here's how you could use that in your scenario:

using (var reader = new System.IO.StreamReader(@"C:\yourfile.txt"))
{
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        if (line.StartsWith("math_"))
        {
            // do something
        }
    }
    reader.Close();
}

You can then put the matching lines in an array and return them in your callMath() method or something like that.

Darkseal
  • 9,205
  • 8
  • 78
  • 111