如何在C#中获取文本文件中的最小值和最大值?

时间:2016-07-06 06:28:16

标签: c#

在文本文件(test.txt)中有值

  

“嗨,这是我的代码项目文件”

Minimum=5maximum=6

我需要外出是

  

最小= 5(“嗨”)

     

最大= 6(“喜欢”)

     

“你好

2 个答案:

答案 0 :(得分:0)

我相信你正在寻找一个函数,它将文本文件读入流中,然后将其解析为字符串变量。完成后,您可以调用stringVariable.substring(0,x)来获取您要查找的输出子字符串。

以下代码演示了这个想法。

  public string void GetSubString(int x)  {
     byte[] buffer;
     FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
      try
      {
        int length = (int)fileStream.Length;  // get file length
        var buffer = new byte[length];            // create buffer
        int count;                            // actual number of bytes read
        int sum = 0;                          // total number of bytes read

        // read until Read method returns 0 (end of the stream has been reached)
        while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
          sum += count;  // sum is a buffer offset for next reading
      }
      finally
      {
        fileStream.Close();
      }

    var str = System.Text.Encoding.Default.GetString(fileStream);

    string sub = str.Substring(0, x);
    return sub;
}

答案 1 :(得分:-2)

以下是杰弗里答案的简单版本:

输出有单引号的原因是因为你不能在双引号中使用双引号而我忘记了如何逃避它们。

int min = 5;
int max = 6;
String s = "'Hi this my code project file'";
String minS = s.Substring(0, min);
String maxS = s.Substring(0, max);
Console.WriteLine(minS);
Console.WriteLine(maxS);