Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceeding String Array length

 
Sean Ellis
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
System.out.println(lineToParse.length());
String[] tokens = lineToParse.split("|");
songList.add(tokens[0]);

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
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm using JDK 1.4.
 
Sean Ellis
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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, \\|.
 
Sean Ellis
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Marc! And thank you for the further explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic