Search code examples
c#textoutput

How would I output part of a text document if I define a starting line and an ending line in C#?


I have a text document containing several different paragraphs of information. An excerpt of this file is included below, along with what I would like to use as the first and ending lines.

INCH TO FOOT (first line)
Divide inch measurement by 12.
END OF INCH TO FOOT (last line)

FOOT TO INCH (first line)
Multiply foot measurement by 12.
END OF FOOT TO INCH (last line)

An example of how I would like the output to appear if a user selects to view the inch to foot conversion formula.

Divide inch measurement by 12.

Any code suggestions would be appreciated. I am currently out of my league with this, and I have no idea where to start.

I have attempted to loop, but all I have managed is to output the full contents of the file.


Solution

  •     using System;
        using System.IO;
    
        public class ConversionFormulaExtractor
        {
            public string GetConversionFormula(string conversionType)
            {
                string filePath = "path_to_your_text_document.txt"; // Replace with the actual file path
                string startLine = conversionType + " (first line)";
                string endLine = "END OF " + conversionType + " (last line)";
    
                string[] lines = File.ReadAllLines(filePath);
                int startIndex = -1;
                int endIndex = -1;
    
                for (int i = 0; i < lines.Length; i++)
                {
                    if (lines[i].Contains(startLine))
                    {
                        startIndex = i + 1;
                    }
                    else if (lines[i].Contains(endLine))
                    {
                        endIndex = i;
                        break;
                    }
                }
    
                if (startIndex != -1 && endIndex != -1)
                {
                    string[] formulaLines = new string[endIndex - startIndex];
                    Array.Copy(lines, startIndex, formulaLines, 0, endIndex - startIndex);
                    string formula = string.Join(Environment.NewLine, formulaLines).Trim();
                    return formula;
                }
                else
                {
                    return "Conversion formula not found.";
                }
            }
        }
    
        class Program
        {
            static void Main()
            {
                string conversionType = "INCH TO FOOT";
                ConversionFormulaExtractor extractor = new ConversionFormulaExtractor();
                string conversionFormula = extractor.GetConversionFormula(conversionType);
                Console.WriteLine(conversionFormula);
            }
        }