ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

CSVSplit

Given a line from a CSV-encoded file, split it into fields.

Source

private enum CSVSplitState
{
    Normal,
    InQuotes,
    InQuotesFoundQuote
}

public static IEnumerable<string> CSVSplit ( this string s )
{
    CSVSplitState state = CSVSplitState.Normal;
    StringBuilder token = new StringBuilder();
    foreach ( char c in s )
    {
        switch ( state )
        {
            case CSVSplitState.Normal:
                if ( c == ',' )
                {
                    yield return token.ToString();
                    token = new StringBuilder();
                }
                else if ( c == '"' )
                    state = CSVSplitState.InQuotes;
                else
                    token.Append ( c );
                break;

            case CSVSplitState.InQuotes:
                if ( c == '"' )
                    state = CSVSplitState.InQuotesFoundQuote;
                else
                    token.Append( c );
                break;

            case CSVSplitState.InQuotesFoundQuote:
                if ( c == '"' )
                {
                    token.Append( c );
                    state = CSVSplitState.InQuotes;
                }
                else
                {
                    state = CSVSplitState.Normal;
                    goto case CSVSplitState.Normal;
                }
                break;
        }
    }
    yield return token.ToString();
}

Example

"this,\"that, those\",\"the other\", "embedded\"\"quote\"" =>

string[] {
    "this",
    "that, those",
    "the other",
    "embedded\"quote" 
}

Author: David Bakin

Submitted on: 8 mrt 2009

Language: C#

Type: System.String

Views: 6067