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.

1 Answer 1

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: "\\|"
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very, much! how do I escape it, isn't double quote enough?
It worked right away, I was so sceptical to ask, being afraid of down voting. Thank you very much again!
+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 \\|
@JBNizet: thanks for your lucid explanation! Sorry for not adding something like it in my initial post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.