Hello guys,
I have a text file which I have to read it from my code which is Ok.
THE PROBLEM :
the program has to read the file and just take and extract or print some part of the text file.
it means Strings between 2 Words.

Here is the content of the text file:
// #Name
// Behrooz 123_box_2000
// ...
// ...
// .....
// #Requirements
// lab_121, lab_222, lab_312
// ...
// ...
// .....
// #Name
// John 555_box_2010
// ...
// ...
// .....
// #Requirements
// lab_666, lab_819, lab_731

AND I need to print out just :

// #Name
// Behrooz 123_box_2000
// #Requirements
// lab_121, lab_222, lab_312

// #Name
// John 555_box_2010
// #Requirements
// lab_666, lab_819, lab_731


I appreciated if you can help me.
BR,
Behrooz.

Dani AI

Generated

The goal is to extract each record that starts with the comment marker for a name and ends with the requirements marker — in the example those are the lines starting with "// #Name" followed by the name line, then "// #Requirements" and the labs line. A reliable approach is to scan the file line-by-line, detect the "#Name" marker (case-insensitive), collect lines until the "#Requirements" marker, include the requirements line and the following non-empty line, then repeat for the next record.

The C# snippet posted by (and noted by ) contains a few concrete problems that prevent it from working:

  • tag strings do not match the file (case and name differences), so Array.IndexOf will not find the start tag.
  • the loop uses the string length (myString.Length) instead of the array length, causing index errors.
  • no check for Array.IndexOf returning -1 (missing start tag) before using the index.
  • the built-up result is never written to the console.
    Fixing those and using defensive checks will make the original approach work; an alternative is the simple Python scanner below.
def extract_blocks(path):
    with open(path, 'r', encoding='utf-8') as f:
        lines = [ln.rstrip('\r\n') for ln in f]
    i, n = 0, len(lines)
    blocks = []
    while i < n:
        if '#name' in lines[i].lower():
            block = [lines[i]]
            i += 1
            while i < n and '#requirements' not in lines[i].lower() and '#name' not in lines[i].lower():
                block.append(lines[i])
                i += 1
            if i < n and '#requirements' in lines[i].lower():
                block.append(lines[i])
                i += 1
                if i < n and lines[i].strip():
                    block.append(lines[i])
                    i += 1
            blocks.append(block)
        else:
            i += 1
    return blocks

for b in extract_blocks('test.txt'):
    print('\n'.join(b))
    print()

Notes: matching is case-insensitive and keeps the original comment slashes. Adapt the marker strings if the file uses different tokens or if requirements span multiple lines. For very large files, a streaming generator (yielding blocks as found) or a small regular-expression search can be used instead.

Recommended Answers

All 2 Replies

This is a pretty easy task. What have you tried so far? We don't do your assignments for you.

I have done this by myself and I didn't get any result! :(

namespace readAndSearch
{
    class read_Search_2
    {
        public static void Main()
        {
            string tagStart = "// #NAME";
            string tagEnd = "// #COUNTER";
            StreamReader myFile = new StreamReader(@"test.txt");
            string myString = myFile.ReadToEnd();

            string[] array = myString.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            int start = (Array.IndexOf(array, tagStart)) + 1; //+1 means that we get rid of #NAME line
            int end = 0;

            for (int i = start; i < myString.Length; i++)
            {
                string item = array[i];
                if (item == tagEnd)
                {
                    end = i;
                    break;
                }
            }


            string result = null;
            for (int i = start; i < end; i++)
                result += array[i] + " ";
            Console.ReadKey();
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.