ides
ides

Reputation: 369

question regarding the usage of split() in java

I'm trying to split() a line of text and numbers from a .txt file. I need to segregate the different parts of the line so that i could insert it inside a database table. Here's an example line:

051500000711000,051500000711000,equal;

I already have working code for this line which is:

String delimiter = (",|;");
temp = strLine.split(delimiter);

but there are times when the sample line would be like this:

052000000711000,,,

See the missing values? They are missing because the other program that generates this line has null values; that's why it only returned commas.

The question is what should i do with my delimiter so that it would read the commas and return it into my split() array as null.

Upvotes: 0

Views: 415

Answers (5)

Stephen C
Stephen C

Reputation: 718906

It is not the delimiter regex that is the problem. Use String.split(regex, limit) with a limit of -1. The default limit is zero which trims trailing nulls from the String array returned by the splitter.

Read the linked javadoc for the gory details.

Upvotes: 8

Bohemian
Bohemian

Reputation: 425073

I think you want this regex:

String delimiter = ",";

Use like this:

temp = strLine.replace(";", "").split(delimiter);

Upvotes: 0

paulsm4
paulsm4

Reputation: 121669

Actually, it should already pretty much work that way.

If an intermediate value in the list is "null"... then you'll get an empty string... which you can simply TREAT as "null".

Here's an example:

import java.io.*;

class X
{
  public static void main (String[] args) throws IOException
  {
    // Prompt user to enter something
    String delimiter = ",|;";
    String sLine = "051500000711000,,051500000711000,A,,";
    String[] sOut = sLine.split (delimiter);
    for (int i=0; i < sOut.length; i++)
     System.out.println ("sOut[]=" + sOut[i]);
  }
}

> sOut[]=051500000711000 
> sOut[]= 
> sOut[]=051500000711000 
> sOut[]=A

Upvotes: -1

maaartinus
maaartinus

Reputation: 46432

Don't use it. Get guava and use Splitter.on(separator).split(string) which solves this and other problems nicely.

Upvotes: 0

Nishant
Nishant

Reputation: 55866

Look into Apache Commons 2.5 StringUtils' splitPreserveAllTokens

Upvotes: 1

Related Questions