Ekrem Tapan
Ekrem Tapan

Reputation: 23

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

Upvotes: 0

Views: 293

Answers (2)

Kvam
Kvam

Reputation: 2218

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);
}

Upvotes: 0

Hamed
Hamed

Reputation: 1213

You can get lines of your csv file using the following.

string[] lines = File.ReadAllLines(pathToCSVFile);

Then, you can split each line and analyse its containing.

for(int i = 0; i < lines.Length; i++)
{
   string[] fields = lines[i].Split(" ", StringSplitOptions.RemoveEmptyEntries);

   // analyse the fields
}

Not that the number of elements in fields can be considered as a hist that whether the line contains Data or not.

Upvotes: 2

Related Questions