如何有效地将文本文件中的值拆分到我的程序中?

时间:2013-03-17 10:38:44

标签: c# arrays string char

我有一个文本文件,我必须用每个空格('')和换行符('\ n')拆分值。它不能很好地工作,因为每个换行都有一个回车连接到它(\ r \ n)。

char[] param = new char[] {' ','\n','\r'}; // The issue
string[] input = fill.Split(param);

param数组不接受'\ r \ n'参数作为n split参数,这就是我分别使用'\ n'和'\ r'的原因,但它不能像它需要的那样工作。有什么建议吗?

4 个答案:

答案 0 :(得分:0)

使用the overload of String.Split() that takes an array of strings代替带有一系列字符的重载。

答案 1 :(得分:0)

an overload that accepts strings

string[] input = fill.Split(
    new string[] { " ", Environment.NewLine },
    StringSplitOptions.None);

您也可以使用Environment.NewLine代替"\r\n"

但是如果你想支持所有类型的行结尾,你最好指定所有流行的可能性:

string[] input = fill.Split(
    new string[] { " ", "\n", "\r\n" },
    StringSplitOptions.None);

答案 2 :(得分:0)

string[] result = text.Split(new string[] { " ", Environment.NewLine },
                            StringSplitOptions.None);

答案 3 :(得分:0)

string fill = @"one two three four";
string[] result = fill.Split(new string[] { " ", Environment.NewLine },
                            StringSplitOptions.None);

foreach (var s in result)
{
    Console.WriteLine(s);
}

这是DEMO

但请记住,Environment.NewLine

  

对于非Unix平台或字符串包含“\ r \ n”的字符串   包含Unix平台的“\ n”。