4

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!

Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
James
  • 161
  • 1
  • 2
  • 12

4 Answers4

9

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".

Community
  • 1
  • 1
Micer
  • 8,731
  • 3
  • 79
  • 73
3

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.

jeremyjjbrown
  • 7,772
  • 5
  • 43
  • 55
2

You need to escape the character. Use "\\|".

More information on regex escaped characters here.

Community
  • 1
  • 1
AntonH
  • 6,359
  • 2
  • 30
  • 40
0
        String test ="freshness|originality";
        String[] splits = test.split("\\|");
        String part1 = splits[0]; // freshness
        String part2 = splits[1]; // originality
user3161879
  • 103
  • 1
  • 17