如何在C#中定义起始行和结束行后输出文本文档的一部分?

huangapple go评论71阅读模式
英文:

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

问题

我有一个包含多个不同段落信息的文本文档。以下是文件的一部分摘录,以及我想用作开头和结尾的内容。

英寸到英尺(第一行)
将英寸测量值除以12。
英寸到英尺结束(最后一行)

英尺到英寸(第一行)
将英尺测量值乘以12。
英尺到英寸结束(最后一行)

如果用户选择查看英寸到英尺转换公式的输出,我希望输出如下所示的示例。

将英寸测量值除以12。

任何代码建议都将不胜感激。我目前在这方面超出了我的能力范围,不知道从哪里开始。

谢谢!

英文:

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.

Thanks!

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

答案1

得分: 1

以下是翻译好的代码部分:

string source = @"INCH TO FOOT
Divide inch measurement by 12.
END OF INCH TO FOOT

FOOT TO INCH
Multiply foot measurement by 12.
END OF FOOT TO INCH

CELSIUS TO FAHRENHEIT
Multiply Celsius temperature by 9/5
Add 32
END OF CELSIUS TO FAHRENHEIT
";

// 收集标识符
List<string> identifiers = new List<string>();
	
using (StringReader sr = new StringReader(source))
{
    bool nextIsIdentifier = true;
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        if (nextIsIdentifier)
        {
            identifiers.Add(line);
            nextIsIdentifier = false;
        }
        else if (string.IsNullOrWhiteSpace(line))
        {
            nextIsIdentifier = true;
        }
    }
}

// 打印标识符,带有索引号
for (int i = 0; i < identifiers.Count; i++)
    Console.WriteLine($"{(i + 1)}. {identifiers[i]}");

// 询问用户选择的索引
Console.Write($"输入数字 1  {identifiers.Count}");
int index = int.Parse(Console.ReadLine());
// 注意:当用户输入非整数或超出范围时,会失败
Console.WriteLine(index);

var identifier = identifiers[index-1];
Console.WriteLine($"Instructions for '{identifier}':");

// 查找说明
using (StringReader sr = new StringReader(source))
{
    string line;
    bool inParagraph = false;
    while ((line = sr.ReadLine()) != null)
    {
        if (line == identifier)
        {
            // 下一行是说明的开头
            inParagraph = true;
        }
        else if (line == "END OF " + identifier)
        {
            // 说明结束
            break;
        }    
        else if (inParagraph)
        {
            // 这是一行说明
            Console.WriteLine(line);
        }
    }
}

请注意,代码中包含一些HTML转义字符(如"),它们在代码中用于表示引号。如果需要实际使用代码,请确保将这些HTML转义字符替换为实际的引号字符。

英文:

As this looks like homework, I will first provide just the outline.

When you know you want the instructions for "FOOT TO INCH", assuming there may be multiple lines of instructions:

  • Declare a boolean variable to mark when you are in the conversion paragraph you want. Set it to false initially.
  • Read the file line-by-line
  • Check whether the line is the conversion you want. If so, set that boolean variable to true.
  • Else, when the line is "END OF " + your conversion, end the loop
  • Else, when that boolean variable is true, print the line

How can the user select the specific conversion? You can print a list of available conversions and ask for one.

First get the list of conversions, assuming the first one starts at the first line and the rest after an empty line:

  • Declare a boolean variable nextIsIdentifier and set to true
  • Declare a list to fill: List<string> identifiers = new List<string>();
  • Read the file, line-by-line
  • When nextIsIdentifier is true, add this line to identifiers and set nextIsIdentifier to false
  • Else, when the line is empty, set nextIsIdentifier to true

When the loop is done, that identifiers contains all conversions.

Now print that list, including an index number. You can ask the user for an index and then start searching the file for the instructions (see above).


Sample code

string source = @"INCH TO FOOT
Divide inch measurement by 12.
END OF INCH TO FOOT

FOOT TO INCH
Multiply foot measurement by 12.
END OF FOOT TO INCH

CELSIUS TO FAHRENHEIT
Multiply Celsius temperature by 9/5
Add 32
END OF CELSIUS TO FAHRENHEIT
";

// gather the headers
List<string> identifiers = new List<string>();
	
using (StringReader sr = new StringReader(source))
{
	bool nextIsIdentifier = true;
	string line;
	while ((line = sr.ReadLine()) != null)
	{
		if (nextIsIdentifier)
		{
			identifiers.Add(line);
			nextIsIdentifier = false;
		}
		else if (string.IsNullOrWhiteSpace(line))
		{
			nextIsIdentifier = true;
		}
	}
}

// print the headers, with an index
for (int i = 0; i < identifiers.Count; i++)
	Console.WriteLine($"{(i + 1)}. {identifiers[i]}");

// ask the user for an index
Console.Write($"enter number 1..{identifiers.Count}: ");
int index = int.Parse(Console.ReadLine());
// NB this will fail when the user inputs a non-integer or one outside the range
Console.WriteLine(index);

var identifier = identifiers[index-1];
Console.WriteLine($"Instructions for '{identifier}':");

// find the instructions
using (StringReader sr = new StringReader(source))
{
	string line;
	bool inParagraph = false;
	while ((line = sr.ReadLine()) != null)
	{
		if (line == identifier)
		{
            // next line is the start of the instructions
			inParagraph = true;
		}
		else if (line == "END OF " + identifier)
		{
            // done with the instructions
			break;
		}	
		else if (inParagraph)
		{
            // this is one line of instructions
			Console.WriteLine(line);
		}
	}
}

答案2

得分: 0

以下是翻译好的部分:

最简单的方法是使用正则表达式:

string? TryParseInchToFoot(string text)
{
    var parser = new Regex(
    @"INCH TO FOOT
    (.*)
    END OF INCH TO FOOT");

    var result = parser.Match(text);
    return result.Success
        ? result.Groups[1].Value
        : null;
}

这是用法示例:

var sourcePath = "{YOUR_PATH_HERE}";
var source = File.ReadAllText(sourcePath);
var inchToFoot = TryParseInchToFoot(source);

我建议从老师那里学习如何处理文件格式,但无论如何,在实际生活中更容易使用数据交换格式,比如 JSON。这是有关如何在 .NET 中使用 JSON 的文章 - 如何在 .NET 中使用 JSON

英文:

The easiest way is using regex:

string? TryParseInchToFoot(string text)
{
    var parser = new Regex(
@"INCH TO FOOT
(.*)
END OF INCH TO FOOT");

    var result = parser.Match(text);
    return result.Success
        ? result.Groups[1].Value
        : null;
}

And here is the usage example:

var sourcePath = "{YOUR_PATH_HERE}";
var source = File.ReadAllText(sourcePath);
var inchToFoot = TryParseInchToFoot(source);

I suggest it's study work with file format from a teacher, but anyway in real life it's much easier to use data-interchange formats like json. Here is the article - how to use json in .net

答案3

得分: 0

读取每一行,直到达到第一行,然后输出下一行

var lines = File.ReadAllLines("文件名");
for (int i = 0; i < lines.Length; i++) {
    if (lines[i] == "INCH TO FOOT")
        break;
}
if (i < lines.Length) {
    var found = lines[i++];
    // 这里你有了你想要的那行
}
英文:

read line by line till you reach the first line, then output the next line

   var lines = File.ReadAllLines(&quot;file name&quot;);
   for(int i = 0; i &lt; lines.Length; i++){
        if (lines[i] == &quot;INCH TO FOOT&quot;)
             break;
    }
    if (i &lt; lines.Length){
       var found = lines[i++];
       // here you have the line you want
    }

答案4

得分: 0

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

(Note: I've replaced the HTML entities with the actual code text in the translation.)

英文:
    using System;
    using System.IO;

    public class ConversionFormulaExtractor
    {
        public string GetConversionFormula(string conversionType)
        {
            string filePath = &quot;path_to_your_text_document.txt&quot;; // Replace with the actual file path
            string startLine = conversionType + &quot; (first line)&quot;;
            string endLine = &quot;END OF &quot; + conversionType + &quot; (last line)&quot;;

            string[] lines = File.ReadAllLines(filePath);
            int startIndex = -1;
            int endIndex = -1;

            for (int i = 0; i &lt; lines.Length; i++)
            {
                if (lines[i].Contains(startLine))
                {
                    startIndex = i + 1;
                }
                else if (lines[i].Contains(endLine))
                {
                    endIndex = i;
                    break;
                }
            }

            if (startIndex != -1 &amp;&amp; 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 &quot;Conversion formula not found.&quot;;
            }
        }
    }

    class Program
    {
        static void Main()
        {
            string conversionType = &quot;INCH TO FOOT&quot;;
            ConversionFormulaExtractor extractor = new ConversionFormulaExtractor();
            string conversionFormula = extractor.GetConversionFormula(conversionType);
            Console.WriteLine(conversionFormula);
        }
    }

huangapple
  • 本文由 发表于 2023年6月1日 10:18:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定