java string split is not giving expected result

I'm trying to split a string into a string [] but im not getting the expected result. What is wrong here?

    String animals = "dog|cat|bear|elephant|giraffe";
    String[] animalsArray = animals.split("|");

I would expect that animalsArray contained the following:

    animalsArray[0] = "dog"
    animalsArray[1] = "cat"
    animalsArray[2] = "bear"
    ...

but it contains only:

    animalsArray[0] = "d"
    animalsArray[1] = "c"
    animalsArray[2] = "b"
    ...

Upvotes: 1

Views: 105

Answers (3)

Mengjun
Mengjun

Reputation: 3197

Have a try using \\|

import java.util.Arrays;

public class Main {

public static void main(String[] args) {
    String animals = "dog|cat|bear|elephant|giraffe";
    String[] animalsArray = animals.split("\\|");
    System.out.println(Arrays.toString(animalsArray));
}
}

Output in Console:

[dog, cat, bear, elephant, giraffe]

Upvotes: 0

vandale
vandale

Reputation: 3650

String.split()splits around a regular expression, not just an ordinary string so you have to escape the "|" (because it has special meaning) and do it as follows:

split("\\|")

Upvotes: 3

rgettman
rgettman

Reputation: 178333

The split method takes a regular expression as its argument, and | has special meaning. Escape it with a backslash, and escape the backslash itself for Java:

String[] animalsArray = animals.split("\\|");

This page lists special symbols in Java regular expressions. Look for | in the "Logical Operators" section.

Upvotes: 3

Related Questions