Is there any library API or regex pattern to split a String on some delimiter and automatically trim leading and trailing spaces from every element without having to loop the elements?
For example, on splitting " A B # C#D# E # "
on #
the desired output is [A B,C,D,E]
The closest I got is str.split("\\s*#\\s*")
which gives [ A B, C, D, E]
As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.
To remove extra spaces before and/or after the delimiter, we can perform split and trim using regex: String[] splitted = input. trim(). split("\\s*,\\s*");
Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.
Just trim it before you split
" A B # C#D# E # ".trim().split("\\s*#\\s*")
The spaces after the commas in [ A B, C, D, E]
are just the way Arrays.toString
prints
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