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 开发者_Go百科= (",|;");
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.
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.
Look into Apache Commons 2.5 StringUtils' splitPreserveAllTokens
Don't use it. Get guava and use Splitter.on(separator).split(string)
which solves this and other problems nicely.
I think you want this regex:
String delimiter = ",";
Use like this:
temp = strLine.replace(";", "").split(delimiter);
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
精彩评论