Re: splitting a CSV line in half



Rex Mottram wrote:
This should be a fairly simple programming task but I just can't find an elegant way to do it. Given a String of (say) 9 comma-separated values:

"f1,f2,f3,f4,f5,f6,f7,f8,f9"

I need to split it such that the first 4 fields are in one String and the rest in the other:

"f1,f2,f3,f4" and "f5,f6,f7,f8,f9"

I'm currently using String.split() to break it into an array of 9 Strings and then using a StringBuilder to paste them back together as above, but that's too ugly to be allowed to live. Can anyone suggest a more elegant technique?

You could write a regex that matched the first four
fields and the first three commas, use the Matcher's
lookingAt() method to match it to the start of the String
and find the length of the matched portion, and then use
a couple of substring() calls to extract the two halves.

Or you could write a regex that matches the first
four fields and three commas in one group, matches the
fourth comma, and matches the remainder in a second group.
Then you'd use the match() method followed by group() calls.

... but something in my parsimonious Yankee soul rebels
at dragging out all this machinery for such a simple task;
it's canaricide by cannon. I'd probably use four indexOf()
calls to locate the fourth comma, and then two substring()
calls to split the string.

--
Eric.Sosman@xxxxxxx
.



Relevant Pages

  • Re: READ comma delimited data
    ... Mike 寫道: ... Or, I should keep finding the rest of the commas on a iterated process, ... where i is the current location, and j is the length of the string. ... a substring) rather than a file. ...
    (comp.lang.fortran)
  • Re: READ comma delimited data
    ... Or, I should keep finding the rest of the commas on a iterated process, ... where i is the current location, and j is the length of the string. ... a substring) rather than a file. ... Gary Scott ...
    (comp.lang.fortran)
  • RE: Help with replacement pattern
    ... replace the commas which are not contained within a pair of quotes. ... After all the "" pairs are matched, any commas in the remaining string ... bool isInQuotes = false; ... Microsoft Online Community Support ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: chop, separate, split a STRING into sections?
    ... code looping such as DO WHILE or FOR NEXT. ... Public Function Chunk(ByVal str As String, ByVal chunkSize As Integer) As String ... an "elegant" solution. ... While first off, I don't see the problem with mid, substring, or looping:) ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Text file I/O in VBA
    ... the commas are also handled well into your cleaned ... Dim f1 As Integer ... Dim fInput As String ... Input #1, strLIne ...
    (microsoft.public.access.modulesdaovba)