|
|
|||||||||
|
|||||||||
|
|||||||||
| |
||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Splitting a csv file w/commas in a field
I have a comma delimited file with fields that have commas. I don't know how to get the split function form splitting when a field has a comma in it. I tried to put quotes around string values but the split function still splits into an element in an array.<br><br>my code<br><br>strInput="123,testdata,testdata with a comma ,,last field"<br>arrArray = strInput.Split(",")<br><br>what I want is:<br>arrArray(0)=123<br>arrArray(1)=testdata<br>arrArray(2)=testdata with a comma ,<br>arrArray(3)=last field<br><br>what I get is:<br>arrArray(0)=123<br>arrArray(1)=testdata<br>arrArray(2)=testdata with a comma <br>arrArray(3)=<br>arrArray(4)=last field<br><br>Can someone help?<br><br>Thanks,<br><br>James
|
|
#2
|
|||
|
|||
|
If you hadn't said that the comma was part of the data item, there would have been no way of us knowing. How do you expect a program to know? Try delimiting your file with something else.
If you want to put the value in quotes to get around it, you'll need to parse the data manually and set a flag when you are inside a quoted block. eg in nearly pseudocode Code:
ArrayList table = new ArrayList();
foreach ( string row in the_rows ){
ArrayList thisrow = new ArrayList();
bool inQuotes = false;
int lastCommaIndex = 0;
for( int i = 0; i< row.length; i++ ){
if(row.substring(i,1) == "\""){
inQuotes = ! inQuotes;
}
if( row.substring(i,1) == "," && !inQuotes){
thisrow.Add( row.substring( lastCommaIndex, i-lastCommaIndex ));
lastCommaIndex = i;
}
}
table.Add((string[])thisRow.ToArray(typeof(string)));
}
return (string[][])table.ToArray(typeof(string[]));
it's untested but that'll (crudely) give you a 2d array representing each item. |
![]() |
| Viewing: ASP Free Forums > Programming > .NET Development > Splitting a csv file w/commas in a field |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|