Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string and trim every element

Tags:

java

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]

like image 573
Somu Avatar asked Nov 02 '11 20:11

Somu


People also ask

How do I split a string into multiple parts?

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.

How Use trim and split in Java?

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*");

What does Strings trim () method do?

Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.


1 Answers

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

like image 119
Garrett Hall Avatar answered Oct 01 '22 19:10

Garrett Hall