This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Exceeding String Array length Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exceeding String Array length" Watch "Exceeding String Array length" New topic

Exceeding String Array length

Sean Ellis

Joined: Aug 22, 2007
Posts: 4
I'm reading from a .txt file, splitting on a pipe "|", and then adding a token (with a specific index) to a String array.

Code Snippet:
String[] tokens = lineToParse.split("|");

When entering this function, the variable lineToParse (String) is equal to the line read in from the file. Here is a sample linetoParse:

1053|"P"|"Stuff"|""|""|"NONE"|"WORKING"|""|""|""|"444 PARK STREET"|""|"VIRGINIA"|"VA"|"22222"|""|""|""|""|""|""|""|""|""|""|""|""|""|""|""|""|""|""|""

The lineToParse.length is 153.

The output when I do a println is (there are several lines being read in from the file):
[, , , , , , , ]

I would expect to see:
[1053, 1111, 22222, 33333, 44444, 55555, etc...]

Am I exceeding some boundary for String array? Any suggestions?
Sean Ellis

Joined: Aug 22, 2007
Posts: 4
I'm using JDK 1.4.
Sean Ellis

Joined: Aug 22, 2007
Posts: 4
Ugh. I truly am an idiot.

String[] tokens = lineToParse.split("|");

Should be:

String[] tokens = lineToParse.split("\\|");

I need to read the API better. Sorry.
marc weber

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Sean Ellis:
...Should be:
String[] tokens = lineToParse.split("\\|");...

I'm glad you got it!

For anyone following, the String argument in String's split method is treated as a regex Pattern (see java.util.regex.Pattern). In this context, the pipe character has special meaning as a logical "or." To get a literal pipe in a String literal, you need the double escape sequence, \\|.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Sean Ellis

Joined: Aug 22, 2007
Posts: 4
Thanks Marc! And thank you for the further explanation.
I agree. Here's the link:
subject: Exceeding String Array length
It's not a secret anymore!