从txt文件拆分行

时间:2014-05-27 11:26:03

标签: c# split string-formatting

我正在尝试从文本文件中分割每一行

每一行都是这样的:

string text=3,"dac","fsdf,sdf","DdsA 102-13",62.560000000000002,"1397","bes","165/70/R13",945,1380,"Break",10

我需要拆分它,需要获得这12列。 有没有办法拆分并获得12列?你可以看到有些部分也含有"," (逗号)

3 个答案:

答案 0 :(得分:2)

 public static String[] SplitCsv(String value)
    {            if (Object.ReferenceEquals(null, value))
            return null;
        const Char quotation = '\"';
        const Char separator = ',';
        List<String> result = new List<String>();
        Boolean inQuotation = false;
        Boolean isStarted = false;
        StringBuilder Sb = new StringBuilder();
        foreach (Char Ch in value)
        {
            if (inQuotation)
            {
                Sb.Append(Ch);
                inQuotation = Ch != quotation;
                continue;
            }

            if (Ch == separator)
            {
                result.Add(Sb.ToString());
                Sb.Length = 0;
                isStarted = true;
            }
            else
            {
                Sb.Append(Ch);
                isStarted = false;
                inQuotation = Ch == quotation;
            }
        }

        if (isStarted || (Sb.Length > 0))
            result.Add(Sb.ToString());

        return result.ToArray();
    }

答案 1 :(得分:-1)

尝试这样的事情:

string s = "3,dac,fsdfsdf,DdsA 102-13,62.560000000000002,1397,bes,165/70/R13,945,1380,Break,10"
string[] words = s.Split(',');
foreach (string word in words)
{
    Console.WriteLine(word);
}

string.Split()方法将返回一个字符串数组,通过该参数,您可以指定分割原始字符串的字符。

<强>更新

好的,请看answer。 从那里稍微修改过的代码:

public IEnumerable<string> SplitCSV(string input)
{
    Regex csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);

    foreach (Match match in csvSplit.Matches(input))
    {
        yield return match.Value.TrimStart(',');
    }
}

string s = "3,\"dac\",\"fsdf,sdf\",\"DdsA 102-13\",62.560000000000002,\"1397\",\"bes\",\"165/70/R13\",945,1380,\"Break\",10";
var words = SplitCSV(s);
foreach (string word in words)
{
    Console.WriteLine(word); 
}

关于如何将其应用于文件中的所有行:

var lines = System.IO.File.ReadAllLines(@"inputfile.txt");
foreach (var line in lines)
{
    var wordsInLine = SplitCSV(line);
    // do whatever you want with the result...
}

答案 2 :(得分:-1)

string[] lines = System.IO.File.ReadAllLines(@"textfile.txt");
string result[][];

foreach (string line in lines)
{
    string[] splitedLine = line.Split(',');
    result.Add(splitedLine);
}

结果是一个包含所有分割线的数组(您的行可以有不同的单词数)

然后,您可以保存到文本文件中或执行您想要的操作

相关问题