Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
split() is based on regex expression, a special attention is needed with some characters which have a special meaning in a regex expression. The special character needs to be escaped with a "\" but since "\" is also a special character in Java, you need to escape it again with another "\" !
The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.
use \\| instead of | to escape it.
String.split
expects a regular expression argument. An unescaped |
is parsed as a regex meaning "empty string or empty string," which isn't what you mean.
Because the syntax for that parameter to split is a regular expression, where in the '|'
has a special meaning of OR, and a '\|'
means a literal '|'
so the string "\\|"
means the regular expression '\|'
which means match exactly the character '|'
.
You can simply do this:
String[] arrayString = yourString.split("\\|");
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