permaculture playing cards*
The moose likes Java in General and the fly likes Split using tab delimiter Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Split using tab delimiter" Watch "Split using tab delimiter" New topic
Author

Split using tab delimiter

lava ayan
Greenhorn

Joined: Apr 24, 2009
Posts: 2
I am trying to read a file line by line and
use the java split funtion on tab , to split a line into individual fields.

Eg: File contains

Field1 Field2 Field3
Sun Moon Star
Moon

I use split("/t", 3). It is fine when the line has 3 fields

When the the field1 is empty and there is a tab before field2, it ignores the tab.
When the last field is empty but if there is a tab after second field , it ignores the tab.

I want to be able to use the split function to recognize the fact that there was an empty string when the first or last field is empty.

It is also my observation that , when I use a split with pipe delimiter (|) , it recognizes the absence of the first and last field.

ie.
Field1 | Field2 | Field3
Sun | Moon | Star
|Moon|

Am I missing something when using the tab with split , that will give me the same behavior as other delimiters

like(|)?
Moojid Hamid
Ranch Hand

Joined: Mar 07, 2009
Posts: 120
Am I missing something when using the tab with split , that will give me the same behavior as other delimiters


A little testing shows exact same results for both delimiters:




Here is what is get:


To solve the problem of empty trailing fields you can initialize variables with default values(or empty strings).
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
> When the the field1 is empty and there is a tab before field2, it ignores the tab.

works OK for me, sure its a tab you have there

> When the last field is empty but if there is a tab after second field , it ignores the tab.

use the -1 argument in split()


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38001
    
  22
I presume by "split" you mean String#split()? If you read the API it tells you what the individual members of the array are:
. . . each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.
So it you start with the delimiter, what will the first member of the array be?
lava ayan
Greenhorn

Joined: Apr 24, 2009
Posts: 2
Thanks for your responses
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38001
    
  22
You're welcome
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Split using tab delimiter
 
Similar Threads
How To Sort Multiple Columns
How to read properties with no key giving
Incompatibility problems when altering serialized objects
Sorting by 3 variables dynamically in arrayList
java uniqueId creation