如何用逗号阅读文本,然后用逗号写?

时间:2015-01-05 17:06:49

标签: 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);

感谢任何帮助。

5 个答案:

答案 0 :(得分:2)

你在线阅读两次;你应该只读一次。您可以通过使用循环对正文的条件检查的存储值来完成此操作,或者更简单地使用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();
}

答案 1 :(得分:1)

如果你需要做的就是写出来,你就不需要付出太多努力了:

while ((text = input.ReadLine()) != null)
{
    Console.WriteLine(text.Replace(","," "));
} 

答案 2 :(得分:1)

使用streamread是这样的.Net 1(恕我直言),使用文件静态来读取/写入/处理您的数据而不访问任何流:File methods。使用此行将所有数据读入字符串缓冲区:

string data = File.ReadAllText(@"c:\c#\inp.txt");

下面显示了在读取数据后如何处理逗号:

//string data = File.ReadAllText(@"c:\c#\inp.txt");

string data = @"2, 4, 7, 8, 15, 17, 19, 20
1, 5, 13, 14, 15, 17, 19, 20";

Console.WriteLine (data.Replace(",", string.Empty));

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

答案 3 :(得分:0)

请注意,您正在阅读该行两次:

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

看起来你可以用一个简单的while循环替换它:

while ((text = input.ReadLine()) != null)
{
    // ...
}

答案 4 :(得分:0)

我可能不正确,因为我自己是新手但你可能需要一个缓冲读卡器而不是流读卡器。

在Java中,我会使用Scanner()方法打开并读取文本文件,然后使用Replace()方法删除逗号。

希望这有帮助。