Search code examples
c#asp.netcsvreader

String Split On CSV asp.net C#


A574A02211 S193FDRA3 20141023S17337 WAN HAI 307

A024A13787 S1023F S1023F WAN HAI 316

A574A02181 S187FDRA3 20141024S17337 WAN HAI 307

i have a csv file like that as above but,

nextCellPlace = FindNextCell(data[dataCounter], spacePlace);
spacePlace = data[dataCounter].IndexOf(" ", nextCellPlace);
arrivalShip.Add(GetCellValue(data[dataCounter], nextCellPlace, spacePlace));enter

im using this code get a third column data, but i wantto slipt front date data and string data, like that this

A574A02211,S193FDRA3,20141023,S17337,WAN HAI 307

if met at no date data i wantto write down NULL then goto continue get second data

like that this

A574A02211,S193FDRA3,20141023,S17337,WAN HAI 307

A024A13787,S1023F,NULLDATE,S1023F,WAN HAI 316

A574A02181,S187FDRA3,20141024,S17337,WAN HAI 307


Solution

  • There are a few cases that makes a simple .Split(' ') not work: blank values and values containing spaces. How about defining an array of indexes where you want to split your data, then run a set of substring operations to split it the way you want? This will also allow you to split in the middle of words such as 20141023S17337 => 20141023, S17337.

    var input = @"A574A02211     S193FDRA3     20141023S17337     WAN HAI 307
    A024A13787     S1023F                S1023F     WAN HAI 316
    A574A02181     S187FDRA3     20141024S17337     WAN HAI 307";
    
    var positionsToSplitOn = new int [] { 0, 15, 29, 37, 48 };
    
    var lines = new List<List<string>>();
    foreach (var line in input.Split('\n'))
    {
        var columnValues = new List<string>();
        for (int i = 0; i < positionsToSplitOn.Length - 1; ++i)
        {
            columnValues.Add(line.Substring(positionsToSplitOn[i], positionsToSplitOn[i + 1] - positionsToSplitOn[i]).Trim());
        }
        columnValues.Add(line.Substring(positionsToSplitOn[positionsToSplitOn.Length - 1]).Trim());
        lines.Add(columnValues);
    }