I am having problems with the java string.split method.
I have a string word like so, which equals- freshness|originality
. I then split this string like so:
String words[] = word.split("|");
If I then output words[1], like so:
t1.setText(words[1]);
It gives me the value f. I have worked out that this is the f in the word freshness
.
How can I split the string properly so that words[1] is actually originality
? Thanks for the help!
You should escape it:
String words[] = word.split("\\|");
Check this explanation in similar question here: Why does String.split need pipe delimiter to be escaped?
String object's split()
method has a regular expression as a parameter. That means an unescaped |
is not interpreted as a character but as OR and means "empty string OR empty string".
You need to escape the pipe because java recognizes it as a Regular Expression OR Operator.
line.split("\\|")
"|"
gets is parsed as "empty string or empty string," which isn't what you are trying to find.
For the record
... ? . + ^ : - $ *
are all Regex Operators and need to be escaped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With