Re: splitting a CSV line in half
- From: Eric Sosman <Eric.Sosman@xxxxxxx>
- Date: Wed, 07 May 2008 10:23:06 -0400
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
.
- Follow-Ups:
- Re: splitting a CSV line in half
- From: Logan Shaw
- Re: splitting a CSV line in half
- From: Rex Mottram
- Re: splitting a CSV line in half
- References:
- splitting a CSV line in half
- From: Rex Mottram
- splitting a CSV line in half
- Prev by Date: Re: How to control the output of the console?
- Next by Date: Re: splitting a CSV line in half
- Previous by thread: splitting a CSV line in half
- Next by thread: Re: splitting a CSV line in half
- Index(es):
Relevant Pages
|