c# - 如何阅读带逗号的文本,然后在不带逗号的情况下书写?

标签 c#

我有一个 txt 文件,其中包含以逗号分隔的数字。

例子:

2, 4, 7, 8, 15, 17, 19, 20
1, 5, 13, 14, 15, 17, 19, 20

等等。

我想把它们写在屏幕上,但没有逗号。 喜欢:

2 4 7 8 15 17 19 20
1 5 13 14 15 17 19 20

我有这段代码,但它只写出奇数行,我需要所有的文本。

        StreamReader input = new StreamReader(@"c:\c#\inp.txt");
        string text;
        string[] bits;
        int x;
        do
        {
            text = input.ReadLine();
            bits = text.Split(',');
            for (int i = 0; i < 8; i++)
            {
                x = int.Parse(bits[i]);
                Console.Write(x + " ");
            }
            Console.WriteLine();

        } while ((text = input.ReadLine()) != null);

感谢任何帮助。

最佳答案

您正在阅读该行两次;您应该只阅读一次该行。您可以通过使用循环体的条件检查的存储值来完成此操作,或者更简单地通过使用 EndOfStream 作为循环条件。

如果连一行都没有,您还应该使用 while,而不是 do/while:

StreamReader input = new StreamReader(@"c:\c#\inp.txt");
while (!input.EndOfStream)
{
    string text = input.ReadLine();
    string[] bits = text.Split(',');
    for (int i = 0; i < 8; i++)
    {
        int x = int.Parse(bits[i]);
        Console.Write(x + " ");
    }
    Console.WriteLine();
}

关于c# - 如何阅读带逗号的文本,然后在不带逗号的情况下书写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27784402/

相关文章:

c# - 使用 DialogResult c# 启动进程

c# - Newtonsoft.Json 用下划线替换空格 C# to JSON Serialize

c# - 验证元素的未转义长度

c# - 模棱两可的扩展方法

c# - 使用Session变量来防止未经授权的访问是否安全

c# - .Net与Bolt URI的连接失败,但Neo4jClient失败,但Neo4j.Driver失败

C# HASP登录代码

c# - 如何将第二个触发器函数添加到部署的 azure 函数而不删除现有函数?

c# - 如何更改数字反序列化的默认类型?

c# - 解决方案中存在冲突的对象名称