Java String Split by “|”

ou must use:

String [] temp = s.split("\\|");

This is because the split method takes a regular expression, and | is one of the special characters. It means ‘or’. That means you are splitting by '' or '', which is just ''. Therefore it will split between every character.

You need two slashes because the first one is for escaping the actual \ in the string, since \ is Java’s escape character in a string. Java understands the string like “\|“, and the regex then understands it like “|“.

Leave a Comment