2

I am working over an hour to find a way to explode a string into a string array.

This method have failed for me:

lineFields = str.split("|");
System.out.print(lineFields.length); 

because it gives back an array of equal length to the string it self.

Then I read here that string tokenizer can explode a string, but unfortunately I cannot find a way to access the element randomly like lineFields[1].

I come from php and doing the simpliest things here looks so unusual, and of course I have searched the relative post on this forum, but still nothing close to my needs.

Melsi
  • 1,462
  • 1
  • 15
  • 21

1 Answers1

3
  • Don't try to use StringTokenizer where split(...) should be used.
  • Just because your attempt to use split(...) isn't working doesn't mean that it's the wrong tool for the job.
  • You're using split wrong. Don't forget to escape your pipe, | String: "\\|"
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thank you very, much! how do I escape it, isn't double quote enough? – Melsi Apr 30 '12 at 23:18
  • It worked right away, I was so sceptical to ask, being afraid of down voting. Thank you very much again! – Melsi Apr 30 '12 at 23:21
  • 2
    +1. But I think an explanation is needed on why the pipe must be escaped this way. String.split takes a regex as argument. And the pipe is a logical operator in the regex syntax. To be treated as a literal pipe character, it must be escaped with a backslash. Since the backslash must itself be escaped with another backslash in a String literal, we end up with `\\|` – JB Nizet Apr 30 '12 at 23:22
  • @JBNizet: thanks for your lucid explanation! Sorry for not adding something like it in my initial post. – Hovercraft Full Of Eels Apr 30 '12 at 23:44