【问题标题】:Printing on console depend on content from text file在控制台上打印取决于文本文件中的内容
【发布时间】:2021-08-06 21:26:43
【问题描述】:

我是 C# 新手。我有一个文本文件,其中包含:

[False False False]
[ True False False]
[ True False False]

我如何编写一个在控制台上打印的函数,例如如果该行是“[False False False]”它打印为 0,如果该行是 [True False False] 它打印 1,所以它将是 0 1 1 行。我已经阅读了文本文件并通过函数将其逐行打印到控制台:

public static void PrintData()
        {
            using (var readtext = new StreamReader(@"E:\text.txt"))
            {
                while (!readtext.EndOfStream)
                {
                    string[] lines = File.ReadAllLines(@"E:\text.txt");

                    foreach (string line in lines)
                        Console.WriteLine(line);
                    
                }
            }
        }

【问题讨论】:

  • if (line.IndexOf("True") > 0) Console.WriteLine("1");
  • StreamReader(@"E:\text.txt") 将打开文件,然后File.ReadAllLines(@"E:\text.txt") 将再次打开文件。你不应该这样做,使用readtect.Readline

标签: c# if-statement console txt


【解决方案1】:

所以本质上你只是在寻找字符串“True”? 你可以这样做:

foreach(string line in lines)
{
    if (line.Contains("True")
    {
       Console.WriteLine("1");
    }
    else
    {
        Console.WriteLine("0");
    }
}

【讨论】:

  • Console.WriteLine(line.Contains(line) ? 1 : 0); 而不是if
猜你喜欢
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
  • 2016-06-15
  • 2018-07-06
相关资源
最近更新 更多