【问题标题】:Access a single character from txt file in c#在c#中从txt文件访问单个字符
【发布时间】:2017-05-20 07:57:35
【问题描述】:

如何访问 txt 文件中的单个字符?

代码应如下所示:

char foo = * character x,y *

char foo = * character number x *

我所说的 x 和 y 确实是指 x = 该行中的字符数。 y = 行号。

txt 文件只是一堆 0 和 1,我想知道字符是 0 还是 1。

【问题讨论】:

  • 你的问题对我来说似乎没有多大意义......
  • 当你说“字符”时,你是指特定的编码,还是我们可以假设你在谈论一个字节?
  • @Theraot txt 文件只是一堆 0 和 1,我想知道字符是 0 还是 1。-编辑:x 和 y 我确实是指 x = 字符该行中的数字。 y = 行号。
  • 您可以将字符串作为字符数组访问。
  • 最简单:使用 File.ReadAllLines() 并访问生成的string[]

标签: c# string text


【解决方案1】:

代码:

char GetChar(string sFilePath, int iLineNumber, int iOffset)
{
    using (StreamReader sr = new StreamReader(sFilePath))
    {
        string sLine = string.Empty;
        while (iLineNumber-- > 0)
            sLine = sr.ReadLine();

        return sLine[iOffset - 1];
    }
}

用法:从examplefile.txt的第2行获取第4个字符

char c = GetChar("examplefile.txt", 2, 4);

编辑(根据 Theraot 的评论)- 在 StreamReader 初始化中支持文件编码。

char GetChar(string sFilePath, int iLineNumber, int iOffset, Encoding oEncoding)
{
    using (StreamReader sr = new StreamReader(sFilePath, oEncoding))
    {
        string sLine = string.Empty;
        while (iLineNumber-- > 0)
            sLine = sr.ReadLine();

        return sLine[iOffset - 1];
    }
}

用法:

char c = GetChar(sFilePath, 2, 4, Encoding.UTF8);

【讨论】:

  • 我忘了提到您必须添加自己的验证,因为如果第 2 行中没有第 4 个字符,它将引发异常。
  • +1:由于 OP 说他想要行号和字符,这是要走的路(编辑:除非 OP 需要一些花哨的行分隔符,我对此表示怀疑)。我已删除我的答案以支持您的答案。我想补充一点,StreamReader 具有接受 System.Text.Encoding 的构造函数重载。
  • 谢谢 Theraot,我会将其更改为 StreamReader c-tor,它也可以获取编码。雷蒙德 - 欢迎您。
  • Orel,当我运行我的代码时,我在“return sLine[iOffset - 1];: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.”上收到以下错误。什么可能导致这个问题?我真的不明白你的代码,所以我无法弄清楚。提前致谢。如果我含糊不清,我很抱歉。
  • Orel,我已经想通了对不起哈哈。我习惯说 x,y 但是在你的代码中它是 y,x 即使你解释得很好。再次感谢
猜你喜欢
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多