Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String Split in Java Giving Unexpected Results

I have a series of strings with the following format: "animal || type || area ||".

In Java, I’m trying to split the string so I can just the first part. Everything I have read online says to split the string:

String animalString = "animal || type || area"
String animalArray[] = animalString.split("||")

System.out.println("result = " + Arrays.toString(animalArray));

However, when I split the string it doesn’t merely split based on the ‘||’ division but instead splits every letter:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result = [a, n, i, m, a, l,  , |, |,  , t, y, p, e,  , |, |,  , a, r, e, a,  , |, |]

When I add a delimiter to the split method, it delimits the first part of the string, so that is not effective.

How can I split a string that has the above format so I can get the three words themselves in an array and not just the letters?

>Solution :

You need to double escape them. Once for the String and once for the regex. \\ escapes the slash so it can be passed on to the regex as \| which escapes the |.

The \\s* allows for 0 or more white spaces before and after the ||

String animalString = "animal || type || area";
String animalArray[] = animalString.split("\\s*\\|\\|\\s*");

System.out.println("result = " + Arrays.toString(animalArray));

prints

result = [animal, type, area]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading